Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows from table recursively using JQ

I want to write a recursive function that will delete rows from my table.

I have the number of rows to keep and after that number i want to remove all rows.

for example: I have the number 5 so the first 5 rows need to stay and the rest need to go. (using the row id)

code:

<table id="table">
<tr id="tr1"/>
<tr id="tr2"/>
<tr id="tr3"/>
<tr id="tr4"/>
<tr id="tr5"/>
<tr id="tr6"/>
<tr id="tr7"/>
<tr id="tr8"/>
</table>

I dont know how much rows i will have, thats why i think i need a recursive solution.

like image 613
sortof Avatar asked May 22 '26 20:05

sortof


2 Answers

You can use several different jQuery filter approaches:

var numRows=5;
$('#table tr').slice(numRows).remove();

OR

$('#table tr:gt(' + (numRows-1) + ')').remove();

DEMO

References:

slice() docs

:gt() selector docs

like image 106
charlietfl Avatar answered May 25 '26 10:05

charlietfl


You can use this

$(document).ready(function(){
var deleteAfter =  5
$.each($("#table tr"),function(key,value){
    //do your conditional here
    if(key > deleteAfter-1){
        value.remove();
    }
});

alert("now the table row is "+$("#table tr").length);

});

This is working jsfiddle

I'm sorry if u want to using id as the input please use this instead

$(document).ready(function () {
    //define the id first
    var deleteAfter = $("#tr5");
    var elementNo;

$.each($("#table tr"), function (key, value) {
    if (this.id == deleteAfter.attr("id")){
        elementNo = key;
    }
});

$.each($("#table tr"), function (key, value) {
    //do your conditional here
    if (key > elementNo) {
        value.remove();
    }
});

alert("now the table row is " + $("#table tr").length);
});

And i updated the jsfiddle

like image 45
himawan_r Avatar answered May 25 '26 08:05

himawan_r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!