0

A pretty odd question, but I've been at this for far to much time to even admit now, and I'm seriously confused by it. So, here goes:

When my page loads, I have 3 checkboxes available. There are several categories to pick in a menu on the left, and clicking each of these categories performs a $.getJSON request which builds new checkboxes by appending this code to tbody:

str = '<tr><td><img src="/images/icons/'+icon+'.jpg" alt="'+shrt+'"></td><td>'+labl+'</td><td>'+desc+'<br><span></span></td><td>'+pnts+'</td><td><input type="checkbox" name="status" class="status" '+checked+' id="'+i+'"></td></tr>';
$("#tbody_data").append(str);

Now, on the first page generated on pageload (by php), I'm able to check if a checkbox is checked by doing $("input[type=checkbox]").click(function () { if($(this).prop('checked')) console.log("This Works"); });

However, after I generate a new checkbox from the js mentioned above, I'm not able to do the same action as above. It doesnt notice a single click event, and I have no idea why it isn't working, and it's annoying the bejesus out of me. Even if I do $("body").click(yadiyadi) nothing happens in the console.

Thanks in advance for any tips you might have!

yusijs
  • 867
  • 9
  • 20
  • check this http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements – Dhiraj Mar 07 '15 at 23:47
  • Are you binding the click handler to the newly inserted checkboxes? Or, better yet, [delegate events](http://learn.jquery.com/events/event-delegation/) like so: $(document.body).on("click", "input[type='checkbox']", function() { ... }); – instanceofnull Mar 07 '15 at 23:49

2 Answers2

0

As mentioned by Dhiraj and randombumper above, that did the trick - I tried calling just a .click, document.body on click worked superb. Thanks for the help chaps.

yusijs
  • 867
  • 9
  • 20
0

The reason your .click() function doesn't work is because the code is called before the checkbox exists in the DOM, so no handler can be applied.

use (document).on("click", "yourSelectorHere", function(){//do stuff}); on dynamically created content.

Kevin Grabher
  • 399
  • 1
  • 4
  • 18