0

I have the following fiddle1 http://jsfiddle.net/y6tCt/35/ . I need to build the checkbox list dynamically but for now I have hard coded two rows. When I click on one of the checkboxes it is not invoking the 'change' event.

I would be grateful if someone could take a look and let me know what I have done wrong.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Martin Shinks
  • 115
  • 2
  • 6
  • 16
  • possible duplicate of [jQuery: Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/jquery-event-binding-on-dynamically-created-elements) – Esailija Jun 25 '12 at 12:52

3 Answers3

2

The problem is that your dom is ready before the buildHTML(); has finished running.

Place the call to buildHTML(); as follows

$(document).ready( function() {
     buildHTML();
     $(":checkbox").change(function() {

        alert("here");

     });});
Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
1

you can use jquery live, as it works on dynamically created elements.

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

http://jsfiddle.net/y6tCt/42/

gherkins
  • 14,603
  • 6
  • 44
  • 70
  • 1
    @Martin This does work and is a great solution, but hopefully you understand why your original did not work, if not then please look at some of the answers below which explain in a bit more detail. – Jon Taylor Jun 25 '12 at 15:32
0

Checkout the script its now working, http://jsfiddle.net/y6tCt/46/

here is the script I changed,

buildHTML();
$(":checkbox").click(function() {
            if( $(this).is(':checked') ) {
         alert("Checked");
            } else {
                alert('Unchecked');
            }

        });});
Subhajit
  • 1,929
  • 3
  • 19
  • 21
  • May I suggest that `this.checked` instead of `$(this).is(':checked')` is more efficient, easier to type, and (in my opinion) easier to read... – nnnnnn Jun 25 '12 at 13:02