Checkbox change event not firing
Asked Answered
S

4

14

This is my code:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('.chk').live('change', function() {
      alert('change event fired');
    });
    $('a').click(function() {
      $('.chk').attr('checked', true);
    });
  });
</script>
</head>
<body>
<div class="chkHolder">
  <input type="checkbox" class="chk" name="a" id="a" />
  <input type="checkbox" class="chk" name="b" id="b" />
</div>
<a href="#">check all</a>
</body>
</html>

When I click on the "check all" hyperlink, I want the change event fired for each of the checkboxes. However, that is not happening.

Any ideas?

Many thanks!

Schuler answered 12/9, 2011 at 12:4 Comment(1)
Is the page reloading instead? You might need a return false; or preventDefault() in the click() handerPearsall
D
34

use: $('.chk').attr('checked', true).change();

Live example: http://jsfiddle.net/NRPSA/1/

Destrier answered 12/9, 2011 at 12:8 Comment(2)
Does anyone know why we need to do it explicitly.Ewold
@Ewold because no event is invoked on that element, it is just setting a property. change() triggers the change event.Birchfield
N
7

When you change the attribute also use the following:

$('.chk').trigger('change');

Or in your code like other people have suggested:

$('.chk').attr('checked', true).trigger('change');
Nipper answered 12/9, 2011 at 12:7 Comment(0)
F
3

Try changing

$('a').click(function() {
      $('.chk').attr('checked', true);
});

To -

$('a').click(function() {
      $('.chk').attr('checked', true).trigger('change');
 });

That should force a trigger of the 'change' event.

Working demo - http://jsfiddle.net/ipr101/pwmBE/

Fixative answered 12/9, 2011 at 12:8 Comment(2)
remember that jquery you can chain commands, you don't need to find .chk two timesDewayne
@Dewayne - Thanks, I completely missed that. I've updated the answer accordingly.Fixative
Z
0

try this.

<div id ="chkall"> <a href="#">check all</a> <div>

            $('#chkall a').live("change", function() {
            $('.chk').attr('checked', true);
            });
Zymosis answered 12/9, 2011 at 12:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.