...

View Full Version : javascript reference to form elements with [] in name



botsko.net
12-22-2005, 01:18 AM
Javascript throws an error when I try to reference a form field with [] in the name,

like formname.somefield[].options[]

Some forms have form name="somefield[]" but when I try to reference it that I can't because thye [] produces a script error. Is there anyway to reference this field by name? Using getelementbyid is not an option here...

Mongus
12-22-2005, 01:22 AM
try this:
formname["somefield[]"].options[]

botsko.net
12-22-2005, 06:15 PM
That's calling a form with the name, not an element. I tried document.forms[0].["fieldname[]"][0].anything, but that did not work.

document.forms[0].fieldname[][0].anything - doesn't work
document.forms[0].fieldname[0].anything - doesn't work
document.forms[0].fieldname[].anything - doesn't work

Either it's an invalid name or it's a syntax error. Both ways I have no way of getting the element by its name in javascript.

Mr J
12-22-2005, 11:49 PM
Here's a few variants to try


<form name="f1">
<input type="text" name="t[]" value="1">
<input type="text" name="t[2]" value="2">
<input type="text" name="t[]3" value="3">
</form>



<script>

test1=document.forms[0]["t[]"].value
test2=document.forms[0]["t[2]"].value
test3=document.forms["f1"]["t[]3"].value

test4=document.forms[0][0].name
test5=document.forms[0].elements[1].name

alert(test1+"\n"+test2+"\n"+test3+"\n"+test4+"\n"+test5)

</script>

Mongus
12-23-2005, 01:32 AM
This works in Firefox and IE.

<html>
<body>
<form name="formname">
<input name="somefield[]"/>
</form>
<input type="button" value="Get Value" onclick="alert(document.forms[0]['somefield[]'].value)"/>
</body>
</html>

BTW, my earlier example assumed you were trying to access the form by name due to the info you posted. It should have worked if you tried it like this:

document.formname["somefield[]"].options[]

Basscyst
12-23-2005, 02:07 AM
I prefer:



document.forms['formname'].elements['elementname[]'].options


Basscyst



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum