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 ?
if you have all the buttons inside of a container and you want the same function for all add the click handler to the container
DEMO
I think it will be better if you use a common class name for all and handle click event by that class name.
Or you can handle event by tag name:
This method might effect the function of other buttons which are not included in the group of 50 buttons.
I would apply it to the parent element of the buttons. So if all of the buttons were in
<div id="myButtons">
:The key is to be specific enough that you do not have to specify each selector but not too lose as there may be other buttons, etc. on the page that you do not want to include.
Updated code to include delegation.
You can use following code:
and so on...
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:
Note your selector may need to be more specific to target just these 50 buttons, as @Drewness points out in the comments.
Try