rolodex
rolodex

Reputation: 530

How do I add a row without affecting other tables of the same class?

Here's my script using append:

$("a.addrow").click(function(){
        $(".itemlist").append('<tr><td>Content</td></tr>');
    });

And I have this HTML

<table class="itemlist">
    <tr>
        <td>Content</td>
    </tr>
</table>
<a href="#" class="addrow">Add Row</a>

<table class="itemlist">
    <tr>
        <td>Content</td>
    </tr>
</table>
<a href="#" class="addrow">Add Row</a>

Now the problem is, this will add row to both tables instead of the relevant one. How do I do that? And how do I prevent anchor jumping, since I'm using # for href?

Help is much appreciated.

Upvotes: 0

Views: 73

Answers (1)

nicosantangelo
nicosantangelo

Reputation: 13726

$("a.addrow").click(function(event){
    //Get the first match and append the data, if you want another result, you could use .eq().
    //So .eq(0) === .first()
    $(".itemlist").first().append('<tr><td>Content</td></tr>');

    //Prevent the anchor 'jumping'
    event.preventDefault();
});

Another way to target a specific table would be to add a distinctive class or id, but I guess that's not an option here.

Upvotes: 1

Related Questions