7

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")); 
Xulfee
  • 958
  • 3
  • 13
  • 43
  • add a class like `generatedButton` or whatever you want to these dynamically created button, and then you can use Jan Willem B's answer: http://stackoverflow.com/questions/2864327/get-id-of-element-on-button-click-using-jquery/2864340#2864340 – jigfox May 19 '10 at 10:15
  • Why do you change the id of the button in the first place? I find that a strange thing to do... – RoToRa May 19 '10 at 10:44

4 Answers4

27

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • All dynamic buttons have unique ids and your code is not working. – Xulfee May 19 '10 at 10:13
  • @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 May 19 '10 at 10:41
1
$('.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
  • 3,787
  • 1
  • 25
  • 39
  • @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 May 19 '10 at 09:50
  • 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 May 19 '10 at 10:28
1

You should add click event of the button after document is ready(Loaded):

$(document).ready(function(){
    $("#btnDel").click(function() {
        alert('Button clicked.');
    });
});
Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
0

For any element whether its a button or anything else , we can target it like this

$(document).click(function(e){
    console.log(e.target.id) 
  
})

Here e.target.id gives you the id of the element.

GAURAV JOSHI
  • 659
  • 8
  • 7