Jess McKenzie
Jess McKenzie

Reputation: 8385

ID of non checked checkbox's

How could I get the ids of the unchecked checkboxes?

I have the code below but I seem to be getting a single value in the array that is being used for state

$("input[type='checkbox']").each(function(){
                 if ($(this).is(":checked")) 
                 {
                    checkbox.push($(this).data("id"));
                    state = 1;
                 }else{
                    $("input[type='checkbox']").attr('checked', false);
                    checkbox.push($(this).data("id"));
                    state = 0;
                 }

Upvotes: 0

Views: 324

Answers (2)

PSL
PSL

Reputation: 123739

You can use not to get unchecked ones.

$("input[type='checkbox']").not(':checked').each(function(){
     checkbox.push($(this).data("id"));
});

One issue could be you are doing

$("input[type='checkbox']").attr('checked', false);

in your else condition so probably if your first element goes to else it will result in setting all to unchecked (if attr works fine enough).

If you want an array of 0..1

var checkbox=[], state=[]; 
$("input[type='checkbox']").each(function () {
    var flg = this.checked ? 1 : 0;
    checkbox.push($(this).data("id"));
    state.push(flg);
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

To get an array of unchecked checkboxes

var uncheckedIds = $("input[type='checkbox']").not(':checked').map(function(){
    return $(this).data('id');
}).get();

Upvotes: 0

Related Questions