Xulfee
Xulfee

Reputation: 986

Get id of element on button click using jquery

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")); 

Upvotes: 9

Views: 117433

Answers (4)

GAURAV JOSHI
GAURAV JOSHI

Reputation: 729

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.

Upvotes: 0

Siyavash Hamdi
Siyavash Hamdi

Reputation: 3087

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

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

Upvotes: 3

Jan Willem B
Jan Willem B

Reputation: 3806

$('.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);

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630607

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);
});

Upvotes: 28

Related Questions