I am using .on()
to attach click events to multiple elements that appear on the page dynamically. The problem I have is that when I add .on
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>
</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 a way around this?
Thank you, Ev.
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,
code
bit improved 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')});
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)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With