Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
Nick Law Avatar asked Sep 23 '26 11:09

Nick Law


2 Answers

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);
like image 92
Tats_innit Avatar answered Sep 26 '26 00:09

Tats_innit


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);
like image 37
Selvaraj M A Avatar answered Sep 26 '26 00:09

Selvaraj M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!