Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery assign events to buttons

I have 50 dynamically generated HTML buttons as follows:

<input type="button" id="btn1" name="myButton" value="Click Me" />
<input type="button" id="btn2" name="myButton" value="Click Me" />
:
:
:
<input type="button" id="btn50" name="myButton" value="Click Me" />

Which is the best way to assign click event to all buttons using jQuery?

By using id or by using name attribute ?

like image 858
user3191903 Avatar asked Oct 28 '25 14:10

user3191903


2 Answers

Event listeners cost memory. You have to think carefully about how you should implement the listeners.

1. The straightforward way:

Do not use this

If the behaviour for each button is the same, use a class:

$(".btn").click(function() {
    // Do something
});

If behaviour for each button is different, assign events to different #IDs

$("#btn1").click(function {
    // Do something
});

2. Use .on():

jQuery 1.7 introduced .on() method that wraps all listeners to 1 method.

$("button").on("click", function() {
    // Do something
});

However, we are still binding many listeners on the page.

3. Use a wrapper (use this!):

Wrap your buttons with a div and create one listener for it.

$("#wrapper").on("click", "button", function() {
    // Do something
});

Useful resources:

  • Performance comparison
  • .on()
like image 57
martynas Avatar answered Oct 30 '25 06:10

martynas


Best way would be to delegate to the surrounding container, that way you only have one listener rather than 50. Use .on()

https://api.jquery.com/on/

If you must assign to each button, figure out a way to write only one selector, like this:

$('button').click(function(){});

Note your selector may need to be more specific to target just these 50 buttons, as @Drewness points out in the comments.

like image 38
Willy Avatar answered Oct 30 '25 07:10

Willy