evkorres evkorres - 1 year ago 79
Javascript Question

jquery .on container element attached to multiple selectors

I am using

to attach click events to multiple elements that appear on the page dynamically. The problem I have is that when I add
to a container on the page and want to attach click events to multiple elements in the container, the latter overwrites the previous.

<div id="container">
<!-- elements here appear dynamically -->
<div id="id1"></div>
<div id="id1"></div>

$('#container').on("click", "#id1", function(){});
$('#container').on("click", "#id2", function(){});

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

Is there a way around this?

Thank you,

Answer Source

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

Yes your id is wrong. :)

YOu are using same id i.e. id1 for both elements.

Hope this helps,


bit improved code

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


 $('#container').on("click", "#id1, #id2", function() {


 $('#container').on("click", "#id1", function(){alert('d1')});
   $('#container').on("click", "#id2", function(){alert('d2')});​
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download