1

I have some tr elements in table:

<table>
<tr id="tr_level_1">...</tr>
<tr id="tr_level_2">...</tr>
<tr id="tr_level_3">...</tr>
<tr id="tr_level_4">...</tr>
<tr id="tr_level_5">...</tr>
</table>

In Javascript I have the next variable:

var levels = 3;

I want to delete all tr's where number in id is more than levels. And if levels is more than number of tr's - adding tr's after last.

Thanls a lot.

0

5 Answers 5

4

Working demo

Try this:

var levels = 3;
$("table tr:gt("+(levels-1)+")").remove();

I substract one because this expression ("gt": greater than) is 0-based index.

For the second part of your question try this:

http://www.jsfiddle.net/dactivo/fADHL/

if($("table tr").length<levels){
 //the code here for less than levels
}
else
{
 $("table tr:gt("+(levels-1)+")").remove();    
}
Sign up to request clarification or add additional context in comments.

Comments

2

I think this should complete the answer

var levels = 3;
var $trs = $("table tr");
var currentLevels = $trs.length;
if (currentLevels > levels) {
    $trs.filter(":gt(" + (levels - 1) + ")").remove();
} else if (currentLevels < levels) {
    var t = "";
    for (i = (currentLevels + 1); i <= levels; i++) {
        t += '<tr id="tr_level_' + i + '"><td>' + i + '</td></tr>';
    }
    $trs.parent().after(t);
}

http://jsfiddle.net/c6XWN/1/ <-- levels = 10

http://jsfiddle.net/c6XWN/2/ <-- levels = 5

http://jsfiddle.net/c6XWN/3/ <-- levels = 3

Good luck!

Comments

1

try this

var total = $("#table").find('tr').length;
var levels = 3;
if(levels<=total) {
   for(levels=levels;levels<=total;levels++) {
       $("#tr_level_"+levels).remove();
   }
}
else {
   $("#table").append("<tr id=\"tr_level_"+total+1+"\">..</tr>");
   // this will add the element with tr_level_6 at the end 

}

Comments

1

Maybe this:

function editTr(inVal) {
selector = new RegExp("\d")
var lastID = selector.exec($("table tr").last().attr("id"));
if (lastID > inVal) {
    $("table tr").each(function () {
        if (selector.exec($(this).attr("id")) > inVal) {
            $(this).remove();
        }
    });
}
else if (lastID < inVal) {
    for (x=lastID;x<=inVal;x++) {
        $("table").append("<tr id=\"tr_level_"+x+"\"></tr>")
    }
}
else {
    return null
}

}

Comments

0
var levels = 5;
var lastTr = $('#ranks_percentages tr:last').attr('id');
lastTr = lastTr.split('_');
var lastLevel = lastTr[1];
if (levels < lastLevel) {
   //removing
} else {
   //adding 
}

1 Comment

if (levels < lastlevel) { /* remove */ } else if (levels > lastlevel) { /* add */ } ... you probably don't want to end up with a bunch of same level tr's

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.