Skip to content Skip to sidebar Skip to footer

Looping Through Checkboxes With Javascript

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the server

Solution 1:

Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/

Pretty good link: https://learn.jquery.com/javascript-101/arrays/

Also in your html end your tag /> i.e.

<input class="publish" id="chkBox4" type="checkbox" checked>

rest should help :)

Code

var checkArray = new Array(); 
$('input[type=checkbox]').each(function () {
    this.checked ? checkArray.push("1") : checkArray.push("0");
});

alert(checkArray);

Solution 2:

As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?

var checkArray = [];

$('input.publish').each(function () {
   checkArray.push($(this).is(':checked'));
});

alert(checkArray);

Solution 3:

Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].

Replace checkArray[i] with checkArray[i-1] inside the for bucle


Post a Comment for "Looping Through Checkboxes With Javascript"