Jquery.on container element attached to multiple selectors

I use .on() to attach click events to several elements that appear dynamically on the page. The problem is that when I add .on to the container on the page and want to attach click events to several elements in the container, the latter overwrites the previous one.

 <div id="container"> <!-- elements here appear dynamically --> <div id="id1"></div> <div id="id1"></div> </div> <script> $('#container').on("click", "#id1", function(){}); $('#container').on("click", "#id2", function(){}); </script> 

In the above example, only the click event for id2 works.

Is there any way around this?

Thanks, Ev.

+7
source share
2 answers

Demo http://jsfiddle.net/aRBY4/2/ slight improvement here http://jsfiddle.net/aRBY4/5/

Yes, your id invalid. :)

For both elements the same identifier ie id1 .

Hope this helps,

the code

bit enhanced code

 $('#container').on("click", "#id1, #id2", function() { alert($(this).prop('id')) // you can use --> attr('id') });​ 

or

  $('#container').on("click", "#id1, #id2", function() { alert($(this).attr('id')) });​ 

or

  $('#container').on("click", "#id1", function(){alert('d1')}); $('#container').on("click", "#id2", function(){alert('d2')});​ 
+13
source

Demo https://jsfiddle.net/amol9supe/w18ktftb/3/

 <div id="container"> //Elements here appear dynamically <div id="id1" class="common-id">hulk</div> <div id="id2" class="common-id">rambo</div> </div> <!-- Script Here --> $('#container').on("click", ".common-id", function() { alert(this.id) }); 
+2
source

All Articles