开发者

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开发者_StackOverflow中文版>
</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


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/


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


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();
    }      
});


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.


You can use jQuery's remove()

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜