0

I want to trigger elements while my Checkbox is checked or not checked. it works perfectly fine with :

$('.myCheckbox:checkbox').change(function () {
//..
}

the thing is, that if I create a new checkbox on client, the .change() doesnt trigger.

I tried also :

$('.myCheckbox:checkbox').live('change',function () {

and it doesnt work as well..

does anyone knows whats wrong ?

Krish R
  • 21,556
  • 6
  • 47
  • 57
thormayer
  • 1,020
  • 5
  • 27
  • 47

6 Answers6

2

Try this:

$(document).on('change', '.myCheckbox:checkbox', function() {

});

Btw, live() is deprecated as of jQuery version 1.7, you should use on() instead.

Felix
  • 36,929
  • 7
  • 39
  • 54
2

You should use .on (upgrade your jQuery version to 1.7 for this).

The syntax is:

$('.yourCheckboxContainer').on('change', '.myCheckbox:checkbox', function() {

});
Chris Dixon
  • 9,024
  • 5
  • 32
  • 66
1

Use

$(document).on('change','.myCheckbox:checkbox',function () {
//..
}

As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.

Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script)

Linga
  • 9,691
  • 9
  • 45
  • 91
1

Hey this is a jquery version problem .on has replaced the .live because of some problems, those problems you can see on this link,

What's the difference between jQuery .live() and .on()

and you can write your code like this.

$(document).on('change','.myCheckbox:checkbox',function () {
// your code
});
Community
  • 1
  • 1
Shivam
  • 692
  • 2
  • 10
  • 25
0

Use:

for jquery 1.7 further

$(document).on('change','.myCheckbox:checkbox',function () {
//..
});

for older version

$('.myCheckbox:checkbox').live('change',function () {

});
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
0

How I understood your problem, it's not about .live or .on. It's about if you first add the change listener with your existing code and then add new checkboxes to the page like

$(document).append($("<input type="checkbox" />"));

the change listener doesn't work with it.

This is normal, as the new checkbox doesn't exist when the listeners are added. You have to add the listeners to the new checkboxes when adding them.

$(document).append($("<input type="checkbox" />").change(whatever));
PurkkaKoodari
  • 6,383
  • 5
  • 33
  • 54