Nick Huge
Nick Huge

Reputation: 155

add and remove TR

<table id="tab" border="2">
    <tbody>
        <tr> <td>aaa</td><td>aaa</td></tr>
        <tr> <td>bbb</td><td>bbb</td></tr>
        <tr> <td><select id="sel">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select></td><td>ccc</td></tr>
        <tr> <td>xxx</td><td>xxx</td></tr>
        <tr> <td>yyy</td><td>yyy</td></tr>
        <tr> <td>zzz</td><td>zzzz</td></tr>
    </tbody>
</table>

$("#sel").change(function(){

    if($(this).val() == 'three'){

       $('#tab').append('<tr><td>new</td><td>new</td></tr>');
    }

});

LIVE: http://jsfiddle.net/jSMBZ/4/

How can I modify this script so that if I select three, I add a new <tr> to the table. If I select either one or two, then I need to remove this new <tr> (if it exists).

edit: i updated my example

Upvotes: 0

Views: 306

Answers (5)

aziz punjani
aziz punjani

Reputation: 25776

If you want the new row right below the select, or in other words, you want it to be the first row on the table then you would use prepend instead. Some code below...

$("#sel").change(function(){ 

    if( $(this).val() === 'three' )
        $('#tab').prepend('<tr class="new"><td>new</td><td>new</td></tr>'); 
    else 
        $('#tab tr.new').remove();    

});

Works for me http://jsfiddle.net/PRu6c/

Upvotes: 2

Dennis
Dennis

Reputation: 32598

You can use jQuery's remove()

$('#tab tbody tr').last().remove();

Upvotes: 1

Paul Grime
Paul Grime

Reputation: 15104

You could set class attribute on the <tr> you've added.

I don't know how clever you wanted it, but I've updated your example here.

Upvotes: 1

Samich
Samich

Reputation: 30115

Simply specify some marker for new row. Here I used id: http://jsfiddle.net/jSMBZ/2/

Just remove marked tr if you change to some other value then three

$("#sel").change(function(){ 
    if($(this).val() == 'three'){
       $('#tab').append('<tr id="added"><td>new</td><td>new</td></tr>');
    } else {
       $('#tab tr#added').remove();
    }      
});

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

I'm not sure if this will work for your needs:

I added a class to the newly created row, called new as such:

$('#tab').append("<tr class='new'><td>new</td><td>new</td></tr>");

whenever a selection is made other than three, it simply removes that row:

$(".new").remove();

Full Code:

$("#sel").change(function(){ 

    if($(this).val() == 'three'){
       $('#tab').append("<tr class='new'><td>new</td><td>new</td></tr>");
    }else{
       $('.new').remove(); 
    }        
});

Working Demo

Upvotes: 2

Related Questions