venkat
venkat

Reputation: 131

Click event on table in jQuery

I have html, I need to append a row in a table dynamically, also I need to catch the click event in the append div class. How to achieve this any idea?

JavaScript:

$(document).ready(function() {

    $("#click").click(function() {
        $('table').prepend('<tr> <td>something3</td> <td> <a><div class="s"> s </a> </td></tr>');
    });


    $(".s").click(function() {
        alert("Ok");
    });

});

HTML:

<input type="button" id="click" value="click"/>

<table width='100%'>
    <tr><td>something</td><td>else here</td></tr>
    <tr><td>something2</td><td>else here2</td></tr>
    <tr><td>something3</td><td>else here3</td></tr>
</table>

Upvotes: 2

Views: 2556

Answers (1)

Matt
Matt

Reputation: 75327

See the live() method, it allows you to bind an event for all current, and future elements in the DOM that match the given selector.

 $(".s").live('click', function(){
    alert("Ok");

 });

jQuery docs say:

Attach a handler to the event for all elements which match the current selector, now and in the future


Note that this answer was written in October 2011, when jQuery 1.6.4 was king. live() was deprecated in 1.7 in favour of using on(). The equivalent syntax is now;

 $(document).on("click", ".s", function(){
    alert("Ok");
 });

Upvotes: 5

Related Questions