Sun Dec 27, 2009 4:49 pm - Count Number Of Elements In An Array
#2958
Count Number Of Elements In An Array
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:
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
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
author: Webune Support