jquery dynamically added checkbox not working with change() function

10,201

Solution 1

You have to use liveQuery or live to bind events to dynamically added elements.

$(".otherProductCheckbox:checkbox").live('change', function(){
    alert('test');
});

EDIT To work in IE, you have to use click not change

$(".otherProductCheckbox:checkbox").live('click', function(){
        alert('test');
 });

Solution 2

Since live() is now deprecated as of jQuery 1.7, I thought I'd post the solution that worked for me on the same problem (trigger event when dynamically added checkboxes are changed).

$(document).on('click', '.otherProductCheckbox', function() {
    alert('test');
});
Share:
10,201
estern
Author by

estern

Front End-Designer and Developer.

Updated on July 26, 2022

Comments

  • estern
    estern almost 2 years

    I dynamically load in a few li's that have a label and a checkbox in them to another visible ul. I set the checkboxes to be checked="checked" and i am trying to trigger an event to happen when i change these dynamically inserted checkboxes but nothing occurs.

    Here is the jquery:

    $(".otherProductCheckbox:checkbox").change( function(){
        alert('test');
    });
    

    Here is the html for the dynamically added li's:

    <li class="otherProduct"><input type="checkbox" class="otherProductCheckbox radioCheck" checked="checked"/><label>Product Name</label></li>
    

    Any idea why i cant get the alert to happen when the checkbox changes its checked state?

  • estern
    estern over 13 years
    @Teja Kantamneni: Perfect. Thanks for the direction. Still learning the ins and outs of jquery.
  • Gareth
    Gareth over 13 years
    You're only required to do that if the elements are being added after the event handler has been set up.
  • estern
    estern over 13 years
    @Gareth: yah that makes sense now.
  • estern
    estern over 13 years
    Actually, this doesn't seem to be working in IE, works in Safari and FF... Any ideas?
  • Teja Kantamneni
    Teja Kantamneni over 13 years
    Thats the issue with IE, IE will trigger change event only after the element looses the focus. webbugtrack.blogspot.com/2007/11/…
  • Teja Kantamneni
    Teja Kantamneni over 13 years
    For fix, use click instead of change
  • estern
    estern over 13 years
    @Teja Kantamneni: That did the trick. Thank you again! Tricky stuff
  • Anish
    Anish over 6 years
    document.getElementById('id').live('click',function() { alert('test'); }); It is not working for me.. what "otherProductCheckbox" means here ?