Get item id on button click using jquery

I have a list of dynamically generated buttons, and id is generated at runtime. how can I get the id of the pressed button using jQuery.

Here is the js code

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


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

$("#btnDel").attr("id", "btnDel" + $("#hid").attr("value")); 
+5
source share
3 answers

In your example, it will be like this:

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

Please note that you cannot encode the code that you have, the identifiers must be unique , you will get all kinds of side effects if this is not so, as this is invalid HTML. If you want a click handler for any input, change the selector like this:

$("input").click(function() {
  alert(this.id);
});
+23
source
$('.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);
+1
source

, ():

$(document).ready(function(){
    $("#btnDel").click(function() {
        alert('Button clicked.');
    });
});
0

All Articles