- Forums
- Javascipt
- Count Number Of Elements In An Array
We Will Show You How You Can Count The Number Of Element Values In An Array One By One As Each Element Has Its Own Value You Can Display And Show All Of The Elements In A Single Value Using Loops To Show All The Values For Each Element In Javascript Array [2197], Last Updated: Mon Jun 24, 2024
Webune Support
Sun Dec 27, 2009
1 Comments
515 Visits
previously, we shows you how you can make an array from a form for each field in a web form and then display them values for each element in an array using a for loop,
the only problem on our previous tutorial, was that you had to know how many elements the javascript array had. but there's a better way. how about if you want javascript to determine the amount of elements in each array. well you can by counting how many elements an array contains.
so using our previous javascript code example, we are going to modify it and add this a variable to determine the number of elements our array has. so we use this code in particular to find out how:
var HowMany = document.myform.elements.length;
and here is the code:
<script type="text/javascript" language="javascript">
function submitted(){
var form = document.myform2
for (i = 0; i < form.elements.length; i++) {
alert(document.getElementById(i).value);
}
}
</script>
Colors:
<form name="myform2">
first color: <input type="text" id="0" value="red"><br />
second color: <input type="text" id="1" value="blue"><br />
third color: <input type="text" id="2" value="green"><br /><br />
<input type="button" value="send" onclick="submitted();"/>
</form>
as you can see, the code is simple, you can modify it or change it to however you need to use it
now you can try it with our demo:
Colors:
remember, if you need web hosting. Webune provides web hosting for you with excellent service and support
http://www.java2s.com/Code/JavaScript/Form-Control/UsingtheformelementsArray.htm
https://www.webune.com/forums/count-number-of-elements-in-an-array.html