-1

Dynamically added content not taking alert function. I tried many ways to make this work but i am not able to get it right. I am sharing the fiddle.

Note: Please fork new fiddle when you are editing it.

thanks in advance.

`http://jsfiddle.net/kc5aa/2/`

2 Answers2

4

You just need to bind event using .on() for dynamically generated elements. This will work for normal elements also.

change on click event binding of checkbox to below code :

 $('.container').on("click",'.checkBox',function () {
        if ($('.checkBox').is(':checked')) {
            alert($(this).val())
        }
    });

Working JSFiddle Demo

See this for using .on() for dynamic elements.

Community
  • 1
  • 1
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • Do you have any special reason to delegate the click from the .container instead of, for instance, the document itself ? – Flo Schild Jul 30 '14 at 13:30
  • yes, if I use `document` then it will bind all checkboxes with class="checkBox" inside html and that may get wrong. OP want to target only checkboxes inside `container` div. – Bhushan Kawadkar Jul 30 '14 at 13:33
  • Okay sure, didn't think about it, but is there also any difference at memory level or execution speed for instance ? – Flo Schild Jul 30 '14 at 13:34
  • yes, it creates single handler.. more information is on http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click – Bhushan Kawadkar Jul 30 '14 at 13:35
0

working fiddle

  $(document).on('click','.checkBox', function () {
    if ($('.checkBox').is(':checked')) {
        alert($(this).val())
    }
});
Anil
  • 3,722
  • 2
  • 24
  • 49