in Javascript .. If I have a dynamically generated buttons and I want a generic onClick function. How can I do that ?
<script>
for(i=0;i<something.length;i++){
$('body').append('<button id="btnInit'+i+'" >'+i+'</button>');
}
</script>
I don't want to create a unique onClick function for each button. How can I do a single one that applies to all. e.g display its label text when pressed.
You can do this by using a Javascript feature called "event bubbling". Ancestor elements are notified of events on their descendent elements.
In this case, you can attach a click handler to the body element and all clicks on those buttons will trigger an event handler. The nicest way to do this in jQuery is to use the on method:
$(document.body).on('click', 'button', function() {
alert ('button ' + this.id + ' clicked');
});
This will work no matter when the elements are created – before or after the elements were created.
This does exactly the same thing as the live method, but live uses on behind the scenes and is far less efficient and flexible.
If you are using a lower version than jQuery 1.7, use live()
$('input[name^="btnInit"]').live("click", function(){
alert("clicked");
});
for jQuery 1.7+, use on()
$("body").on("click", "input[name^="btnInit"]", function(){
alert("clicked");
});
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