tags:

views:

84

answers:

4

Using javascript how do I get the number of elements present with the id of id[x]?

Sample HTML:

<input name="vrow[0]" id="vrow[0]" value="0" type="text"/>
<input name="vrow[1]" id="vrow[1]" value="0" type="text"/>
<input name="vrow[2]" id="vrow[2]" value="0" type="text"/>
<input name="vrow[3]" id="vrow[3]" value="0" type="text"/>

The above html is generated depending on user input. How do I detect how many elements are present using javascript?

Currently I can detect presence of an element like this

Sample Javascript

if(document.getElementById('vrow[0]')){
var row=0;
    }
if(document.getElementById('vrow[1]')){
row=1;
    }
...
+5  A: 

[] are not valid characters in ID attributes. You should use the name attribute (without the numeric indexes), and then use getElementsByName():

<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
var vrows = document.getElementsByName("vrow");
alert(vrows.length);

Note that IE and Opera may return elements with id attributes that have the same value as the name specified in getElementsByName(). IE may also return non-input elements with a name attribute that has the same value.

Andy E
FWIW, getElementsByName() isn't supported in IE or Opera. Or rather, it's supported, but not correctly: http://www.quirksmode.org/dom/w3c_core.html
Robusto
thank you. basics matter.
abel
@Robusto: Provided you look out for those issues, there shouldn't be any problems. Updated my answer to reflect that.
Andy E
+1  A: 
var inputTags = document.getElementsByTagName('INPUT');
var count=0;
for(var i=0;i<inputTags.length;i++)
if(inputTags[i].id.contains('vrow[')
count++;
Vinay B R
interesting. but i get a Object does not support this property or method.
abel
A: 

getElementById always returns one element (since id are unique). getElementsByName can result a list of elements.

<html>
<head>
 <script>
  function getElements() {
   var elements = document.getElementsByName("vrow[]");
   alert(elements.length);
  }
 </script>
</head>
<body onload="getElements()">
<input name="vrow[]" id="vrow_0" value="0" type="text"/>
<input name="vrow[]" id="vrow_1" value="0" type="text"/>
<input name="vrow[]" id="vrow_2" value="0" type="text"/>
<input name="vrow[]" id="vrow_3" value="0" type="text"/>
</body>
</html>
Mark Baijens
A: 

If you use a JavaScript library with a query function supporting CSS3, such as Prototype, you can use the attribute starts-with selector to find id attributes beginning with vrow[

So in Prototype this would be

$$('input[id^=vrow[]').each

NB this is untested, you might have to escape the [ in the selector

Prototype $$ function

Mark Chorley