tsohtan
tsohtan

Reputation: 850

How to use Jquery to add click function for run time added image?

i have a HTML table markup which generated on browser when user click. here is the Code

$('#selectedtable > tbody:first').append(
    '<tr > ' +
        '<td>Chair</td>' +
        '<td><img src="/Content/images/showinfo.png" title="Show Info"></td>' +
    '</tr>'
    );

So my question is that possible to add click event for the above generated image?

Upvotes: 0

Views: 1688

Answers (3)

Thierry J
Thierry J

Reputation: 2189

Yes, you can either add the onclick handler just after you added your image to the dom, with

$("#my-image").click(function() {
     alert("I've been clicked");
});

(For an image with an id my-image)

Or you can set a handler that will be applied to all future added elements:

$(document).on("click", ".image-class", function() {
     alert("I've been clicked");
});

(For images with classes .image-class)

Upvotes: 2

Lochemage
Lochemage

Reputation: 3974

It gets added to the DOM, therefore you should be able to select it like you would select any DOM element and add whatever event handlers you want.

Upvotes: 0

j08691
j08691

Reputation: 207901

Assuming that the element with ID #selectedtable exists when the page loads, use .on()'s event delegation syntax:

$('#selectedtable').on('click', 'img', function(){...})

Upvotes: 0

Related Questions