-1

I am looking to add data to a form object which is an array.

This works fine:

<input type="text" name="object" value="">
<script>document.form.object.value = "value";</script>

But when the object is an array it's not working:

<input type="text" name="object[]" value="">
<script>document.form.object[0].value = "value";</script>

The value of the object is not changing.... Any idea?

I would like to loop the script so I need to create an array. Didn't find any solution...

Dries B.
  • 1
  • 1
  • 2
  • 1
    you have a typo..., the second example you didn't spell object correctly. – Ousmane D. Apr 04 '17 at 13:53
  • 1
    The DOM API doesn't see `name="aPrice[]"` as array-like. That's PHP (at least) that transform that server-side. – alex Apr 04 '17 at 13:54
  • Sorry. Was an error in this source code. At the source code both names are the same... aka aPrice[]. The error should be found somewhere else – Dries B. Apr 04 '17 at 13:55
  • If you're looping the script, you don't need to make the `name` attribute an array; just create a loop and assign the value the form object each time through, like `document.form.object.value = myArray[i]`. – freginold Apr 04 '17 at 13:59
  • Possible duplicate of [HTML form input tag name element array with JavaScript](http://stackoverflow.com/questions/3234205/html-form-input-tag-name-element-array-with-javascript) – Quinn Johns Apr 04 '17 at 15:14

2 Answers2

0

Per example, I would utilize document.form.elements['object[]'].value = "value". Otherwise, if you intended on having multiple form elements with the same name (multiple inputs with object[], and iterate via the collection, can use the following:

var myForm = document.form;
var myControls = myForm.elements['object[]'];
for (var i = 0; i < myControls.length; i++) {
    var aControl = myControls[i];
}

The example provided, in your code, the name provided is not perceived as an array.

Community
  • 1
  • 1
Quinn Johns
  • 376
  • 4
  • 16
0

The attribute value "object[]" is just a string to JavaScript -- it does not interpret that as an array. However, when brackets appear in a name, you cannot use it any more in the dot-notation, but must write:

document.form["object[]"].value = "value";
<form name="form">
    <input type="text" name="object[]" value="">
</form>

If you have more than one element with name="object[]", then the above will only target the first one of these. To set the value of all those elements, you must loop. This you can (for instance) do with the elements property and Array.from to iterate over those elements:

Array.from(document.form.elements["object[]"], function(elem) {
    elem.value = "value";
});
<form name="form">
    <input type="text" name="object[]" value="">
    <input type="text" name="object[]" value="">
</form>

For those using IE: replace Array.from with [].map.call

trincot
  • 317,000
  • 35
  • 244
  • 286