PDA

View Full Version : Refer to a input named "data[]"


Lanceli
09-02-2006, 09:32 PM
Hi all,

I have a form with a few <input type="text" name="data[]"/>. I want to make a javascript to change all of their values at once. Please note, I have to use "data[]" as the name of the input. However, it's invalid to use document.forms.myForm.data[].value. So how shall I walk around this problem? How can I refer to that input object?

Here is my code: (only works when input name="data")
<html>
<head>
<script type="text/javascript">
function setvalue()
{
for (i=0; i<document.forms.myForm.data.length; i++){
document.forms.myForm.data[i].value=1;
}
}
</script>
</head>
<body>
<form name="myForm" action="" method="get"
target="_blank">
<input type="text" name="data[]" size="20"><br />
<input type="text" name="data[]" size="20"><br />
<input type="button" onclick="setvalue()" value="set val">
</form>
</body>
</html>

jkd
09-02-2006, 10:01 PM
document.forms.myForm.elements["data[]"]

liorean
09-02-2006, 10:17 PM
It can also be worth notice that names of form controls are supposed to be unique. A form control can consist of one or more input elements of type radio or checkbox, but input elements of type text may not share a name with any other input element.

If they happen to do, the behaviour is undefined - that is, there is no guarantee that more than one of the elements will be submitted. So, even if it happens to work in most browsers, you should avoid it.

Lanceli
09-02-2006, 10:24 PM
document.forms.myForm.elements["data[]"]
Thanks, problem solved

Lanceli
09-02-2006, 10:26 PM
It can also be worth notice that names of form controls are supposed to be unique. A form control can consist of one or more input elements of type radio or checkbox, but input elements of type text may not share a name with any other input element.

If they happen to do, the behaviour is undefined - that is, there is no guarantee that more than one of the elements will be submitted. So, even if it happens to work in most browsers, you should avoid it.

Yeah, you are right if name="data". However, I'm using name="data[]" as array, so they shall be the same.

liorean
09-02-2006, 11:22 PM
Yeah, you are right if name="data". However, I'm using name="data[]" as array, so they shall be the same.
Wrong. There is no difference from the client side between naming several input elements "data" and naming several input elements "data[]". Only one form control may have the same name. That the server treats them as an array of several form controls doesn't mean that they are. To the client "data[]" is a single name, and form control names must, as I said before, be unique.