I have 50 dynamically generated HTML buttons as follows:
I think it will be better if you use a common class name for all and handle click event by that class name.
$('.classname').click(function(){
//`enter code here`
});
Or you can handle event by tag name:
$('button').click(function(){
//'enter code here'
});
This method might effect the function of other buttons which are not included in the group of 50 buttons.
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
$("#container").on("click", function(e){
if(e.target.type =="button")
{
alert(e.target.id);
}
});
<div id="container">
<input type="button" id="test1" value="button1"/>
<input type="button" id="test2" value="button2"/>
<input type="button" id="test3" value="button3"/>
<input type="button" id="test4" value="button4"/>
<input type="button" id="test5" value="button5"/>
<input type="button" id="test6" value="button6"/>
something
<input type="text"/>
</div>
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.
I would apply it to the parent element of the buttons. So if all of the buttons were in <div id="myButtons">
:
$('#myButtons').on('click', 'button' function () {
// Do stuff...
});
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.
This would be an easy way to wrap it all up into one 'on' event and do something based on the button id;
<button id='button1'>button 1</button>
<button id='button2'>button 2</button>
<button id='button3'>button 3</button>
var mybuttons = $('#button1');
for(i=1;i<3;i++){
mybuttons = mybuttons.add($('#button'+i));
}
console.log(mybuttons);
mybuttons.on('click', function(){
var myid = $(this).attr("id");
console.log(myid);
//use a switch or do whatever you want with the button based on the id;
});
here's a fiddle http://jsfiddle.net/gisheri/CW474/1/
You can use following code:
$("#btn1").on("click",function(){
// Your code
});
$("#btn2").on("click",function(){
// Your code
});
and so on...