[Javascript] Form with array like structure
Jonathan Buchanan
jonathan.buchanan at gmail.com
Sun Jul 23 16:31:33 CDT 2006
Peter Lauri wrote:
> Best groupmember,
>
> I have a form that looks something like this:
>
> <form>
> <input type="text" name="thename[]"/>
> <input type="text" name="thename[]"/>
> <input type="text" name="thename[]"/>
> </form>
>
> In regular case, I can use document.getElementByName("thename").value to
> check the value of it, but how do I do now when one name has several. In PHP
> it is treated as an array, but how can I look thru this with JavaScript?
>
> Best regards,
> Peter Lauri
Use the form's "elements" property to access fields by name like so:
yourForm.elements["someName"]
If there is more than one field with the given name, you will get an
Array-like structure back. Here's some sample code and output using the
Javascript Shell bookmarklet [1] with Firefox to interact with a page
containing the example form you gave, with "Cheese" typed into the first
text field:
>>> var form = document.forms[0];
>>> form.elements["thename[]"]
[object NodeList]
>>> form.elements["thename[]"].length
3
>>> form.elements["thename[]"][0]
[object NodeList]
>>> form.elements["thename[]"][0].value
Cheese
Jonathan.
[1] http://www.squarefree.com/shell/
More information about the Javascript
mailing list