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

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.

Related

JavaScript remove class from table rows

I have a table that highlight the tr (row) on click, and I can highlight multi rows on every click but I want to have only one row to be highlight in table. how to remove the highlight class from sibling rows. code below
JavScript
document.querySelector("table").addEventListener("click", function (e) {
// Is it a click on a tr in this table?
var tr = e.target.closest("tr");
if (tr && this.contains(tr)) {
// Yes, toggle highlight
tr.classList.toggle("highlight");
}
});
css
.highlight {
background-color: #ffeaea;
}
If you don't mind I used #CBroe's suggestion here, to remember the previously selected TR:
let prevTr = undefined
document.querySelector("table").addEventListener("click", function (e) {
let tr = e.target.closest("tr");
if (tr && this.contains(tr)) {
if(prevTr) prevTr.classList.remove("highlight")
tr.classList.add("highlight");
prevTr = tr
}
});
I ended up adding below code and issue resolved.
$('.table tr').removeClass("highlight");

jQuery value returned from text() causes unrecognised expression error when adding to array

I have the following code:
$(document).ready(function () {
debugger;
// Empty aarray to store list of headings
var tableHeadings = [];
// For each heading present add it to the array (ordered)
$('#AdvancedTable thead > tr > th').each(function () {
//console.log($(this).text());
$(tableHeadings).add($(this).text());
});
// For each row in the table, add the heading text to the start of each cell
$('#AdvancedTable tbody > tr > td').each(function (index) {
$(this).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
However, one of my table headings I am storing values from contains the text "Length (L1)". I get the following error in my console:
Uncaught Error: Syntax error, recognised expression: Length (L1)
I understand the basics that this is caused by there being issues with text passing something with brackets in it, but would like to know the details of why this happens and a hint as to how I can solve this/best practices to avoid an error like this.
Use map instead of each.
// Empty aarray to store list of headings
var tableHeadings = $('#AdvancedTable thead > tr > th').map(function () {
return this.innerHTML;
}).get();
You are creating an empty array, iterating over elements, and adding them to an array. This is essentially reinventing the wheel for what map already does.
tableHeadings is a simple array, so you can use push function to add value:
$(document).ready(function () {
let tableHeadings = [];
$('#AdvancedTable thead > tr > th').each( (index, item) => {
tableHeadings.push($(item).text())
});
$('#AdvancedTable tbody > tr > td').each( (index, item) => {
$(item).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
$(tableHeadings).add($(this).text());
need to be
tableHeadings.push($(this).text())
Not sure why you're using JQuery to add an item to a list; perhaps try:
tableHeadings.push($(this).text());
instead of the original line:
$(tableHeadings).add($(this).text());

Apply class to parent row, if child cell contains a specific value

Problem
I want to hide a row if a value appears in any of its child cells.
Desired Effect
Apply class to row, if one of its child cells contains a specific value
Bonus Challenge: Hide column containing the value, i.e. "admin-hide"
Example Code
$('tr').each(function(){
if($('td:contains("non-member")', this).length{
$(this).addClass('disabled');
}
});
Why?
Invaluable for tables containing information that needs to be:
toggled on/off without losing the back-end data, i.e. member roster,
with lapsed member rows having display: none;
highlighting particular rows, i.e. premium sponsors
Difficulties I've Faced
Hiding the column is problematic. If necessary, I can stick to just have hiding rows with child elements containing a string.
Tech I've Working w/
Wordpress 3.5.1
Jquery 1.10.1
Tablepress Pluging (which uses DataTables plugin for Jquery)
Attempt #1
This is what I have in the page editor in WordPress:
[table id=3 /]
<script>jQuery(function($) {
$('#tableID tr').filter(function() {
$('td', this).each(function() {
if ($(this).text().indexOf('admin-hide') != -1)
$('#tableID tr td:eq('+ $(this).index() +')').hide();
});
return $(this).text().indexOf('non-member') != -1;
}).addClass('disabled');
});</script>
<style>
.disabled {display: none;}
</style>
Attempt #2 - #adeneo
This hides the row but breaks Datatables/Tablepress:
<script> jQuery(function($) {
$('#tablepress-3 tr:contains("admin-hide")').addClass('disable-cells')
var index = $('td:contains("admin-hide")').index();
$('th,td', '#tablepress-3').filter('nth-child('+(index+1)+')').addClass('disable-cells'); });
</script>
<style>
.disable-cells {display: none;}
</style>
Attempt #3 - #SpenserJ
This hides the row, allows for Datatables. However, it doesn't hide the column.
<script>
jQuery(function($) {
$('#tablepress-3 td').each(function() {
if ($(this).text().indexOf('admin-hide') !== -1) {
// Hide the column without affecting the table formatting
$(this).css('visibility', 'hidden');
}
});
// Hide the entire row
$('#tablepress-3 tr:contains("admin-hide")').hide();
});
</script>
http://codepen.io/SpenserJ/pen/GqviI
jQuery(function($) {
$table = $('#tablepress-3');
$('th, td', $table).each(function() {
if ($(this).text().indexOf('Admin Only') !== -1) {
var index = $(this).index();
$('th:eq(' + index + '), td:eq(' + index + ')', 'tr', $table).hide();
}
});
// Hide the entire row
$('tr:contains("Membership Expired")', $table).hide();
});
jQuery(function($) {
$('#tableID tr').filter(function() {
$('td', this).each(function() {
if ($(this).text().indexOf('admin-hide') != -1)
$('#tableID tr td:eq('+ $(this).index() +')').hide();
});
return $(this).text().indexOf('non-member') != -1;
}).addClass('disabled');
});
Something like this?
// tr that contains the specific word - add class to
$('#tableid tr:contains("specific word")').addClass('yourclass');
// get column index of admin-hide
var index = $('#tableid td:contains("admin-hide")').index();
// and hide all th/tr in that column
// this is assuming when you initialized datatables you named it oTable as in var oTable = $('table').datatables()
oTable.fnSetColumnVis( index, false ); // for datatables
// or if you want to manually hide them
$('th,td', '#tableid').filter(':nth-child('+(index+1)+')').css('visibility','hidden');
If you are using dataTables - you can set visibility like this example. Also remove the +1 because the index for the method is 0 based also - http://www.datatables.net/examples/api/show_hide.html
using oTable
manually hiding visibility
using hide() works fine - i don't know why it was messing up your sorting
$('th,td', '#tablepress-demo').filter(':nth-child(' + (index + 1) + ')').hide()
$('table .classForRowThatCouldBeHidden').find('.someClassForHiddenValue').parent().hide();

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: Get <td>'s html only

i have this code. It returns all the td code including the td /td tags. I want it to only return the content/html of the td
<td>Hey</td>
should give me just
Hey
jQuery("#ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr", tr).map(function (index, td) {
return jQuery(td).html();
});
});
The jQuery code gives me an array looking like this:
arr[0] = {"<td>1</td>", "<td>Hey</td>", "<td>Some data</td>" }
arr[1] = {"<td>2</td>", "<td>There</td>", "<td>Some other data</td>" }
From html looking like this:
<table id="ReportTable"><tr><td>1</td><td>Hey</td><td>Some data</td></tr><tr><td>2</td><td>There</td><td>Some other data</td></tr></table>
So the array is good except that i only need the html / text inside the td's.
You need to go down one more level in your selector, like this:
jQuery(".ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr td", tr).map(function (index, td) { return jQuery(td).html(); });
});
Or, just use .text() instead or .html(), like this:
jQuery(".ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr", tr).map(function (index, td) { return jQuery(td).text(); });
});
(I have ".ReportTable" instead of "#ReportTable", as comments noted on the question IDs need to be unique...so you should use class="ReportTable" if there are multiple)
It seems to me that the simplest solution would be to work directly on the TDs instead of selecting their parent first. Does the code below solve the problem? (I could have mis-understood - apologies if that's the case!)
jQuery("#ReportTable td", html).each (function (index) {
arr[index] = jQuery(this).html();
}
So why not select the TD instead of the TR in your selector and work from there? jQuery's html() function leverages htmlElement.innerHtml, so you shouldn't have any problems once you select the correct elements.

Categories

Resources