Nida
Nida

Reputation: 1702

Exclude disabled checkboxes when using Select All

I have checkboxes with labels in table. I have added one checkbox outside the table "Select All" with id "chkbox". Now the below code is working fine. It is Selecting and Deselecting all the checkboxes in the table. Now there are some pages where some checkboxes are disabled due to business logic. I want these checkboxes should not be affected.

<script type="text/javascript">
var s = jQuery.noConflict();
s(document).ready(function() {
    s('#chkbox').change(function() {
        var all = s('table').find('input[type="checkbox"]');
        if (this.checked) {
            all.prop('checked', true);
        } else {
            all.prop('checked', false);
        }
    });
});
</script>

Upvotes: 2

Views: 2114

Answers (1)

Tushar
Tushar

Reputation: 87203

Use :not() with :disabled selector.

var all = $('table').find('input[type="checkbox"]:not(:disabled)');
                                                 ^^^^^^^^^^^^^^^^

This will not select the disabled checkboxes

$('#selectAll').change(function() {
  $(':checkbox:not(:disabled)').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" id="selectAll" />Select All

<ul>
  <li>
    <input type="checkbox" disabled />
  </li>
  <li>
    <input type="checkbox" />Not disabled</li>
  <li>
    <input type="checkbox" />Not disabled</li>
  <li>
    <input type="checkbox" disabled />
  </li>
  <li>
    <input type="checkbox" />Not disabled</li>
</ul>


You can also use :enabled selector.

$('table').find('input[type="checkbox"]:enabled')

$('#selectAll').change(function() {
  $(':checkbox:enabled').prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" id="selectAll" /> Select All

<ul>
  <li>
    <input type="checkbox" disabled />
  </li>
  <li>
    <input type="checkbox" />Not disabled</li>
  <li>
    <input type="checkbox" />Not disabled</li>
  <li>
    <input type="checkbox" disabled />
  </li>
  <li>
    <input type="checkbox" />Not disabled</li>
</ul>

Note that: :enabled == :not(:disabled)

Upvotes: 11

Related Questions