Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding onClick event to dynamically generated buttons?

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.

like image 873
Morano88 Avatar asked Aug 01 '26 15:08

Morano88


2 Answers

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.

like image 73
lonesomeday Avatar answered Aug 04 '26 10:08

lonesomeday


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");
 });
like image 28
Shyju Avatar answered Aug 04 '26 08:08

Shyju



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!