Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are some values in my array undefined

I have a for loop in php that adds a number of checkboxes on my page that look like this

<input type="checkbox" name="checkbox[]">

I want to use javascript to check which is checked and add value in an Array

var cboxes = document.getElementsByName('checkbox[]');
var len = cboxes.length;
var imageArray = new Array();

for (var i = 0; i < len; i++) {
    if (cboxes[i].checked) {
        imageArray[i] = cboxes[i].value;
    } 
}

If I have 50 boxes and click the checkbox number 2,4 and 6, loops through my array, I get the result.

for(var i = 0; i < imageArray.length; i++){
    gallery.innerHTML += imageArray[i] + "<br>";
}

--

undefined
Correct value
undefined
Correct value
undefined
Correct value

If I check number 1, 2, 3 I get the result

Correct value
Correct value
Correct value

Why do I get undefined when I skip a checkbox? How do I fix it

like image 949
Xtreme Avatar asked Oct 18 '25 01:10

Xtreme


2 Answers

This is because you are adding extra elements to an array. Take this code, for instance:

var a = []; // empty array
a[1] = 'foo'; // don't set a[0]

console.log(a.length); // gives 2

Javascript will always "fill in" gaps in the list of array keys. If you miss some out, Javascript will fill in the blanks with undefined.

Rather than adding the element to your array by the key name, just push it onto the end of the array:

imageArray.push(cboxes[i].value);
like image 120
lonesomeday Avatar answered Oct 19 '25 15:10

lonesomeday


You get undefined because you're skipping indexes in imageArray. If the first checkbox isn't checked, it won't put anything in index 0, then because the second checkbox is checked, the first entry is placed into index 1.

When you iterate it doesn't skip those missed indexes if there is an index with a value after it, they just don't have a set value so it comes back as undefined.

You could change this line:

imageArray[i] = cboxes[i].value;

to:

imageArray.push(cboxes[i].value);

That way it won't skip indexes when there are unchecked checkboxes.

like image 29
Anthony Grist Avatar answered Oct 19 '25 15:10

Anthony Grist