2

I'm attempting to create a list of checkboxes with an All and None checkbox at the end.

Upon clicking these checkboxes there's quite a heavy operation so it's vital that the checking and unchecking process doesn't cause a click event on each child checkbox!

Here's my JS:

$(document).ready(function(){
  $('#AllCheckbox').click(function(){                               
  $('#NoneCheckbox').removeAttr('checked');
  $('.TypeCheckbox').attr('checked', 'checked');                                        
});

$('#NoneCheckbox').click(function(){
  $('#AllCheckbox').removeAttr('checked');
  $('.TypeCheckbox').removeAttr('checked');                 
});

$('.TypeCheckbox').click(function(){
  alert('Type checkbox was clicked');
  $('#AllCheckbox').removeAttr('checked');
  $('#NoneCheckbox').removeAttr('checked');
  });
});

Here's my html:

<label for="1Checkbox">1</label><input type="checkbox" ID="1Checkbox" class="TypeCheckbox" />
<label for="2Checkbox">2</label><input type="checkbox" ID="2Checkbox" class="TypeCheckbox" />
<label for="3Checkbox">3</label><input type="checkbox" ID="3Checkbox" class="TypeCheckbox" />
<label for="AllCheckbox">All</label><input type="checkbox" ID="AllCheckbox" />
<label for="NoneCheckbox">None</label><input type="checkbox" ID="NoneCheckbox" />

I've created a JSFiddle.

If you click 'All' it works great, all the numbered checkboxes are checked. However click 'None' then 'All' again and the second time the numbered checkboxes are not checked. Why not?

Liath
  • 9,913
  • 9
  • 51
  • 81

4 Answers4

6

Use .prop() instead of .attr()

Example

$('.TypeCheckbox').prop('checked', true/false); 

I very good explanation is given at .prop() vs .attr() do visit it.

Working Fiddle

EDIT:

On second thought I feed you don't need None checkbox see DEMO

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use .prop()

$(document).ready(function () {
$('#AllCheckbox').click(function () {
    $('#NoneCheckbox').prop('checked',false);
    $('.TypeCheckbox').prop('checked', "checked");
});

$('#NoneCheckbox').click(function () {
    $('#AllCheckbox').prop('checked',false);
    $('.TypeCheckbox').prop('checked',false);
});

$('.TypeCheckbox').click(function () {
    alert('Type checkbox was clicked');
    $('#AllCheckbox').prop('checked',false);
    $('#NoneCheckbox').prop('checked',false);
});
});

Demo

Pesulap
  • 884
  • 8
  • 19
1

Use .prop() here is the demo link http://jsfiddle.net/dhana36/7hsQ4/2/

dhana
  • 6,487
  • 4
  • 40
  • 63
0

You should use prop, not attr:

$('#AllCheckbox').click(function () {
  $('input:checkbox').prop('checked', 'checked');
});

$('#NoneCheckbox').click(function () {
  $('input:checkbox').removeAttr('checked');
});
James Hibbard
  • 16,490
  • 14
  • 62
  • 74