View Full Version : Incrementing an array

01-14-2009, 11:23 AM

I am trying to increment an array with a new id value everytime the criteria within my for loop and if statement is met. is my syntax for the array correct? i think the value in the array is being overwritten everytime the loop goes around? any help is most appreciated!

thanks alot


var idStr;

var idArr = new Array ("1","2","3","4","5");

var checkedArray = new Array();

for (i = 0; i < idArr.length; i++) {
idStr = idArr[i];

if (document.getElementById(idStr) != null && document.getElementById(idStr).checked == true){

checkedArray = idStr;

thanks alot

01-14-2009, 04:16 PM
This will do what you want:

var id_arr = ["1","2","3","4","5"];
var checked_arr = new Array();
for (var i=0;i<id_arr.length;i++)
var element_to_check = document.getElementById(id_arr[i]);
if (element_to_check && element_to_check.checked) checked_arr.push(id_arr[i]);

You shouldn't be giving your html elements ids that start with a number though.

Array.push(value) adds value to the end of the array instance.