简体   繁体   中英

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 to saved in a table. I have tried the below code:

<input class="publish" id="chkBox1" type="checkbox" checked>
<input class="publish" id="chkBox2" type="checkbox" checked>
<input class="publish" id="chkBox3" type="checkbox" checked>
<input class="publish" id="chkBox4" type="checkbox" checked>
<input class="publish" id="chkBox5" type="checkbox" checked>

<script>
$('#save-btn').click(function(evt){
    evt.preventDefault();

    var numberOfChBox = $('.publish').length;
    var checkArray = new Array(); 

    for(i = 1; i <= numberOfChBox; i++) {

        if($('#chkBox' + i).is(':checked')) {
            checkArray[i] = 1;  
        } else {
        checkArray[i] = 0;
        }
    }
    alert(checkArray);
});
</script>

but the alert outputs this:

,1,0,1,0,1,1

The values are correct except the first index in undefined. There are only a total of 5 checkboxes and yet the array is 6 indexes long. Why is this?

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

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 /> ie

<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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM