Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select all if not disabled

I am using the following script to select all checkboxes with a given class.

$(document).ready(function(){ // 1
    // 2
    $(':checkbox.selectall').on('click', function(){
        // 3
        $(':checkbox[class='+ $(this).data('checkbox-name') + ']').prop("checked", $(this).prop("checked"));
        $(':checkbox[class='+ $(this).data('checkbox-name') + ']').trigger("change");
    });

});

However I'm having a problem as the de/select all checkbox is able to de/select checkboxes which are disabled.

I tried this

$(document).ready(function(){ // 1
    // 2
    $(':checkbox.selectall').on('click', function(){
        // 3
        $(':checkbox[class='+ $(this).data('checkbox-name') + !$(:disabled) + ']').prop("checked", $(this).prop("checked"));
        $(':checkbox[class='+ $(this).data('checkbox-name') + !$(:disabled) + ']').trigger("change");
    });

});

But it does not work. I have made a jsfiddle to showcase the problem http://jsfiddle.net/e67Fv/

like image 436
user1488434 Avatar asked Jul 12 '12 17:07

user1488434


2 Answers

Hm... interresting attempt, but you can't use a jQuery object inside a selector, as the selector is just a plain string.

The selector for excluding the disabled elements would be :not(:disabled), so your code should be:

$(document).ready(function(){
  $(':checkbox.selectall').on('click', function(){
    $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked"));
    $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change");
  });
});

Note that you can chain calls, so you don't have to select the items twice:

$(document).ready(function(){
  $(':checkbox.selectall').on('click', function(){
    $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked")).trigger("change");
  });
});
like image 179
Guffa Avatar answered Nov 09 '22 23:11

Guffa


Use a combonation of the .not() function and :disabled selector to exclude these.

$(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').prop("checked", $(this).prop("checked"));
$(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').trigger("change");

.not() also exists as a selector as :not() and could be used as follows:

 $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked"));
 $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change");
like image 31
Goran Mottram Avatar answered Nov 09 '22 23:11

Goran Mottram