How can i count form inputs with javascript?

Hi Guys,

How can I count form array inputs like “input_name” using javascript?

formname.getElementsByTagName(‘input’).length

Will that actually count the number of inputs or the length of the input?

that’s how many <input> tags are inside of the form.

formname.getElementsByTagName(‘input’) is an array containing all of the input fields in the form. When you get the length of an array it tells you how many entries are in the array.

 <script type="text/javascript">
window.onload= function count () {
var e = document.forms["form1"] ;
e= e.getElementsByTagName('input');
alert(e.length) ; // 6
var n = document.forms["form1"].elements["aa"].length;
alert(n) ;  // 4
}
</script>
<body>
<form name="form1">
<input type="text" name="aa"><br>
<input type="radio" name="aa"><br>
<input type="checkbox" name="bb"><br>
<input type="password" name="aa"><br>
<input type="image" name="bb"><br>
<input type="submit" name="aa"><br>
</form>

Is there anyway to count only one specific input field?

What do you mean with a specific input field? Of type text etc?

No I mean count all occurences of a specific field name. For example, I have a form that has several inputs with the same name:


<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">

How can I count all occurences of “venue_name”?

  
<body>

<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">

<script type="text/javascript">

var e = document.getElementsByTagName('input');

var i ; 
var s = 0 ;
for(i=0; i < e.length; i++) {

if(e[i].type== "text" && e[i].name=="venue_name[]" ) { s++  ; }
}
 alert ( s ) ;

</script>

Thanks, that worked a treat!

There is no need to use getElementsByTagName in this case, use getElementsByName instead:


<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">
<input name="venue_name[]" type="text">


<script>
var venueInputs = document.getElementsByName("venue_name[]");

alert(venueInputs.length);
</script>