1

I find it weird that the .on() function is firing the event only once/twice upon ajax load.

Here's a sample code:

$(document).on('click', '.cbxCheckAll', function(e) {
alert(this.checked);
$(this).parents('table').find('input.cbxDelete:checkbox').attr('checked', this.checked);
});

Scenario: So basically, I have a dropdown that has a list of users. Upon selecting a user on the dropdown, it instantly loads the selected user's info on a div via ajax. Then on that div, I have multiple checkboxes with a "select all" option.

Upon clicking the "select all", it did select all checkboxes. Another click, it did unchecked checkboxes. Well, it did work. But when I click again (for the 3rd time), it's not working anymore. It seems to be that it only works on the 2nd click.

As you may notice, I have an alert() that displays the value of the "select all" checkbox. It seems to fire everytime I click on it (3rd, 4th, etc.) but the checking/unchecking part is not.

I just recently updated my Jquery version to the lastest (1.9). I was using the ver (1.7) with the .live() function and changed it to .on() since the .live() was removed on the latest.

Thanks in advance!

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
basagabi
  • 4,900
  • 6
  • 38
  • 84
  • 1
    Make sure to use [`console.log()`](http://stackoverflow.com/questions/4743730/what-is-console-log-and-how-do-i-use-it) instead of `alert()` – Dom Mar 06 '13 at 14:51
  • as @Dom stated, alert holds the thread, console.log lets it keep going. – Gonçalo Vieira Mar 06 '13 at 14:54
  • 1
    (possibly) not related to your problem, but ".parents('table')" selects EVERY table ancestor of this element. If you try ".closest('table')" you only select the closest 'table' ancestor. – DoXicK Mar 06 '13 at 14:54

1 Answers1

0

You have to use .prop() in recent versions of jQuery when dealing with the checked property.

$(document).on('click', '.cbxCheckAll', function(e) {
    //alert(this.checked);
    console.log(this.checked);
    $(this).parents('table').find('input.cbxDelete:checkbox').prop('checked', this.checked);
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Thanks Kevin B!!! This works perfectly! Just wondering, why my code stated above doesn't work? I was using this with the jquery 1.7 version and it works perfectly. But now that I upgraded to 1.9, it doesn't anymore? – basagabi Mar 06 '13 at 15:17
  • Yes, this is the reasoning behind it only working twice, although i'm not entirely sure logically why it happens. 1.9 switched back to the more strict .attr/.prop that was introduced in 1.6 and removed in 1.6.1 If you want to research it, be my guest, but you'd be researching why a method doesn't work as expected when you use it in an unexpected way. – Kevin B Mar 06 '13 at 15:23
  • Thanks Kevin. I just saw a discussing about attr vs prop. You guys may check it too. A lot of reading. [link](http://stackoverflow.com/questions/5874652/prop-vs-attr) – basagabi Mar 06 '13 at 15:27