Pawan
Pawan

Reputation: 1744

How to get the id of a dynamically created html button on its click in jquery

I have several(inside loop) dynamically created html buttons like :

sb.Append("<input type=\"button\"  name=\"deleteimage" + id 
              + " \" id=\"btndelete" + id 
              + "\" value=\"Delete\" class=\"t-button t-grid-delete\" " 
              + " style=\"margin-left:10px;\" />");

and I want to get the id of the button on which I click using jquery

Help Me

Thanks

Upvotes: 3

Views: 1449

Answers (5)

Hai Lu
Hai Lu

Reputation: 121

You can try the following:

$(document).click(function(event) { 
        var target = event.target;      
        if ($(target).hasClass("t-grid-delete")) { // check if element has class t-grid-delete is your button
            var targetId =  $(target).attr("id");
            // set your image id with attribute like image_id
            // it take easy to get image id $(target).attr("image_id")
        }
    });

Upvotes: 1

Ankush Jain
Ankush Jain

Reputation: 6974

Use 'live' event for dynamically generated html element's event

$("input[type=button]").live('click',function()
{
    alert(this.id);
});

Upvotes: 0

wirey00
wirey00

Reputation: 33661

delegate using .on()(jQuery 1.7+) or .delegate()(jQuery 1.6 and lower)

$('body').on('click','input[type=button]',function(){
     alert(this.id); // <-- this refers to current clicked input button
});

or

$('body').delegate('input[type=button]','click',function(){
     alert(this.id);
});

Or whatever your sb element is replace body with that since it exists on dom load

Upvotes: 3

Uchenna Nwanyanwu
Uchenna Nwanyanwu

Reputation: 3204

Try this

$("input[type=button]").click(function()
{
    alert(this.id);
});

Upvotes: 1

Justin Harvey
Justin Harvey

Reputation: 14672

How about

$('input:button').click(function(){
    alert('Clicked ' + this.id);

Upvotes: 1

Related Questions