Delete rows from table recursively using JQ - javascript

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.

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

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

you can use :gt() selector, it selects all the elements greater than index and then you can remove it.
$(document).ready(function () {
var index = 4; // set index 4, so want to remove 5 elements( 0 to 4)
$('#table tr:gt('+index+')').remove();
});

Related

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

Selector to find closest DOM elements with attr greater than given

I have table created after AJAX which looks like that:
<tr data-level=2>
<tr data-level=3>
<tr data-level=4>
..etc.
<tr data-level=2>
<tr data-level=3>
<tr data-level=4>
..etc.
of course there may be many cells on any data-level.
I want to hide all rows greater than clicked level to row which level is smaller than clicked one. So - after I click data-level=4 I want to hide all elements with data-level > 4 till I get to row with data-level < 4.
You can use .filter()
Reduce the set of matched elements to those that match the selector or pass the function's test.
Example code
$('tr[data-level]').on('click', function(){
var level = $(this).data('level'); //Get level of clicked element
$('tr[data-level]').filter(function(){
return $(this).data('level') > level;
}).hide();
})
DEMO
Use
$('tr[data-level]').on('click', function () {
var level = $(this).data('level'); //Get level of clicked element
var arr = [];
$(this).nextAll('tr[data-level]').each(function () {
if ($(this).data('level') > level) {
arr.push($(this));
} else if ($(this).data('level') == level) {
return false;
}
});
$.each(arr, function(){
$(this).hide()
});
})
DEMO
Here's another solution
Edit: Sorry, the question wasn't clear, this solution hides all elements with greater value.
HTML
<table id="resultTable">
<tr data-level=2><td>2</td></tr>
<tr data-level=3><td>3</td></tr>
<tr data-level=4><td>4</td></tr>
<tr data-level=2><td>2</td></tr>
<tr data-level=3><td>3</td></tr>
<tr data-level=4><td>4</td></tr>
</table>
JS
$(document).ready(function () {
$("tr","#resultTable").on("click",function() {
var el = $(this);
var clickedValue = parseInt(el.attr("data-level"),10);
hideLargerThan(clickedValue);
});
var hideLargerThan = function(value) {
$("tr","#resultTable").each(function() {
var el = $(this);
var myValue = parseInt(el.attr("data-level"),10);
if(myValue > value)
el.hide();
});
};
});
http://jsfiddle.net/JKurcik/c8Q5Z/2/
you can derive from this code easily.

How to delete the last column of an html table with varying columns

I have a tabulated list of records - an HTML table.
Most rows have 3 columns but some may have just 1 or 2. In this case, I use colspan and stretch it across the other columns.
What I want to do:
When a user clicks a button on the page, I want to remove the last column (collapse), ONLY if it has more than one column.
How is this possible with jquery (if it can be done)?
try something like this
$('tr').each(function(){
$("td:last").hide()
})
You can do this, but you should also add a class to the table so that you can select the table you want by class.
if($('tr').length > 1) {
$('tr').each(function(){
$("td:last").hide()
})
}
If you add for example the class myTable, do:
if($('.myTable tr').length > 1) {
$('.myTable tr').each(function(){
$(".myTable tr td:last").hide()
})
}
try this
$('tr').each(function(){
$("td:last").hide();
})
I think you need to live the save number of columns (colspan) in the row before removing the latest column in order to make table responsive.
Wrote a little function. Not tried in action
<button onclick="removeLatestCol()"></button>
<script>
function removeLatestCol() {
var latest_row = $("table tr:last");
var cols = $("td", latest_row);
if (cols.length == 1) {
latest_row.remove();
return;
}
var latest_col = cols.filter(":last");
latest_col.prev().attr("colspan", (latest_col.prev().attr("colspan") || 1) + (latest_col.attr("colspan") || 1));
latest_col.remove()
}
</script>

jQuery select multiple table columns by index

I've seen certain questions knocking around which are similar, but not exactly the same and I'm stumped with this one.
What I'm trying to do is create a widget that takes a table, then goes through the table's td elements and sets a cursor:pointer (for now) to them, but only the ones that I allow.
This is how my code looks:
selectableGrid: function (options) {
var indexes = options.columns // this is [1,2];
return this.each(function () {
// Make the td's in the grid selectable
$(this).find("tbody td").attr("style", "cursor:pointer");
});
}
The end result I'm wanting to achieve?
<tbody>
<td>hello</td> // index 0
<td style="cursor:pointer">hello</td> //index 1
<td style="cursor:pointer">hello</td> // index 2
</tbody>
Bear in mind that I could be sending through 1,3 in my array list of columns, so lt and gt don't work for my scenario (as far as I've tried anyway).
EDIT:
In order to achieve this I went with the following code:
$(this).find("tr").each(function () {
$(this).find("td").each(function (i, el) {
if (indexes.indexOf(i) > -1) {
$(this).css("cursor", "pointer");
};
});
});
For some reason "tbody td" wouldn't work for a singular loop as it only referenced the first iteration of the tag.
Thank you once again Stack Overflow.
Loop through the td elements, and check that their index with respect to their siblings is an index contained in the options.columns array.
selectableGrid: function (options) {
var indexes = options.columns // this is [1,2];
return this.each(function () {
$(this).find("tbody td").each(function(){
var columnIndex = $(this).index();
if($.inArray(columnIndex, options.columns) != -1){
$(this).css("cursor", "pointer");
}
});
});
}
.each takes an index parameter you can reference in your code.....:
var indexes = options.columns;
this.find("tbody td").each(function(i, el) {
if ($.inArray(i,indexes)>-1) { // good idea, ggreiner
$(this).css("cursor","pointer");
};
});
loop through your indexes and use the http://api.jquery.com/eq/ to find the particular td.

JQuery .addclass to table <tr> element where text is found

I am theming some report tables and do not have access to the templates.
I have this code so far which ends up adding "my-class" to every TR element in the report table. However, I only want to add the class to the table row TR where the text was found. I am thinking I need a little more code to do this. Here are a few things I have tried so far:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$("#reportArea table tr", this).addClass("my-class");
}
I have also tried:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$(this).addClass("my-class");
}
... but that did not work either.
Just use the selector with no fluff:
$('#report-area tr:contains("Name")').addClass('my-class');
http://api.jquery.com/contains-selector/
var $rows = $('#report-area table tr');
$rows.each(function(i, item) {
$this = $(item);
if ( $this.text() == 'Name' ) {
$this.addClass('yourClass');
}
});
I only want to add the class to the table row TR where the text was
found.
You can do:
$('#report-area table tr').each(function(){
if ($.trim($(this).text()).length > 0) {
$(this).addClass("my-class");
}
});
You can also use the .filter() function as well here:
$(document).ready(function () {
$('#report-area tbody tr').filter(function () {
return $.trim($(this).text()).length > 0;
}).addClass("my-class");
});
I like this because it's a little cleaner and limits the number of rows you need to iterate over.

Categories

Resources