IE has a problem with getElementsByName

October 3rd, 2007. Tagged: IE, JavaScript

Yes, it does.

Sometimes it's convenient to use "HTML arrays", meaning to name fields like:
<input name="something[]" />

Then on the server side you loop through the array $_POST['something']

This allows for a flexibility where your app doesn't know the number of inputs in advance, but works fine regardless of the actual number.

Even cooler is that you can generate fields on the client-side, with JavaScript.

The problem is if you want to do some sort of client-side validation after you've generated fields on the fly. If you have:

<input name="something[]" />
<input name="something[]" />
<input name="something[]" />

Then you can access the fields using


So in the case above


will give you 3.

Then you add another fields, for example like:

var new_input = document.createElement('input');
new_input.type = 'text'; = 'something[]';

Now if you try to count the fields with


you'll get 4 in Firefox as you would expect, but still 3 in IE.

Bugs happen, c'est la vie 😀

Here's a demo

Tested IE7 only, don't know if the bug exists in earlier versions.

My example was with an HTML array using []s in field names, but the issue remains if you have regular names without brackets, for example you have radio buttons or checkboxes and you want to create more choices dynamically with JavaScript.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov