tags:

views:

72

answers:

2

i have list of dynamic generated buttons and id is generated on run time. how can is get id of clicked button using JQuery.

Here is js code

var btn = " <input type='button' id='btnDel' value='Delete' />";


$("#metainfo").append(txt); //set value of

$("#btnDel").attr("id", "btnDel" + $("#hid").attr("value")); 
+1  A: 
$('.generatedButton').click(function() {
  alert(this.id);
});

EDIT after you posted the code:

var btn = 
  $("<input type='button' value='Delete' />")
    .attr("id", "btnDel" + $("#hid").val())
    .click(function() {
       alert(this.id);
    });
$("body").append(btn);
Jan Willem B
what is .generatedButton?
Xulfee
@Xulfee this is an example how you can add `generatedButton` (without the dot) to the `class`-attribute of your button to find it with jQuery (http://api.jquery.com/class-selector/)
jigfox
the code you posted in your question does not work (for example, the btn var only contains a string with HTML which would result in a button if it was rendered by a browser, but not the button itself), but I updated this answer in an attempt to help you with it.
Jan Willem B
+1  A: 

For your example it would be like this:

$("#btnDel").click(function() {
  alert(this.id);
});

Note that you can't loop the code you have, IDs have to be unique, you'll get all sorts of side-effects if they're not, as it's invalid HTML. If you wanted a click handler for any input, change the selector, like this:

$("input").click(function() {
  alert(this.id);
});
Nick Craver
All dynamic buttons have unique ids and your code is not working.
Xulfee
@Xulfee - Are you running it **before** you create the button, or after creating it and setting the ID? If it's before, you'll need to use `.live('click', function() {})` instead of `.click(function() { })`
Nick Craver