2

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?

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

+ 1 yes this is legit! :)
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

1 Comment

That's ok but how did the array fill with 6 elements..? totally there are 5 checkboxes right..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.