Table column styling with jquery - javascript

I have a table on my website and i am trying to style it with jquery. the code i am using works fine with normal table but if in a column two cells are merged it destroys the style. I want 1 column to be coloured and one column blank
jquery code
$( document ).ready(function() {
$('#tab-table').find("table").addClass('s-table');
$(".s-table tr td:nth-child(2n+1)").css("background-color","#d1deec");
});
link to fiddle

CSS can help you to draw colonnes background-colors if you use proper markup :
<colgroup>
<col/>
<col/>
</colgroup>
and then basicly apply :
col {background:#789 url(image.png);}
A mixed of background in col , and rgba colors in cells can give you this : http://codepen.io/gc-nomade/pen/ybDhH/
Else , if you do not have hands on markup, trick it and do it from headers cells.
You could use some tricks with box-shadow or pseudo-element from header cells and overflow on table.
Pseudo-element technic :
http://codepen.io/gc-nomade/pen/dDwmf
and box-shadow technic: http://codepen.io/gc-nomade/pen/xqALu

I'd use a loop (if the merged cells will always stay the same..
see fiddle:
http://jsfiddle.net/jFIT/k5yZ9/4/
$("table tr:not(:first)").each(function() {
if($(this).find('td').length == 7)
{
//can replace with array 2/4/6
$(this).find('td:nth-child(2)').css("background-color","#d1deec");
}
else
{
// 3/5/7
$(this).find('td:nth-child(3)').css("background-color","#d1deec");
}
//loop array
});
Update
http://jsfiddle.net/jFIT/k5yZ9/6/
Using array:
$("table tr:not(:first)").each(function () {
var arr = [];
var $this = $(this);
if ($(this).find('td').length == 7) {
arr.push(2, 4, 6);
} else {
arr.push(3, 5, 7);
}
$.each(arr, function (ind, val) {
$this.find('td:nth-child(' + val + ')').css("background-color", "#d1deec");
});
});

Related

Jquery Data table Search Option is not enable sorting icon

I am stuck in jquery Data table. if we use jquery data table then it provide by default search option. But problem is that if i search particular record and if content is not match or i found single record. then i need to remove sorting icon. it will work but as i press back space and remove searching content then as usual it display all records. But now sortable icon is disable it needs to enabled once again then what is the solution for that.
This is function call:-
$('#datatable-information').on('draw.dt', function () {
disableSortingSearchOption(oTable, 'datatable-information_filter input');
This is Function Defination:-
function disableSortingSearchOption(oTables, tableClass) {
if (oTables != null) {
var rowCount = oTables.fnSettings().fnRecordsDisplay();
{
if (rowCount == 0 || rowCount == 1) {
var oSettings = oTables.fnSettings();
//Remove sort icon
$('.DataTables_sort_icon').remove();
//Remove hand cursor
$('.datatable th').css('cursor', 'default');
//Iterate through each column and disable sorting
$('.' + tableClass + ' th').each(function (index) {
if ((oSettings.aoColumns[index]) != undefined) {
oSettings.aoColumns[index].bSortable = false;
}
});
}
}
}
}
Here is a simple way to remove the sorting arrows on the table headers and change the pointer to default when the drawed table has 1 line or less.
On more than one line, the table sorting and the pointer comes back to "normal".
My solution is quite different than the code you provided.
function disableSortingSearchOption(oTables) {
if (oTables != null) {
var colCount = 0;
$(oTables).find('th').each(function(){
colCount++;
});
//console.log(colCount+" colunms");
var rowCount = 0;
$(oTables).find('td').each(function(){
rowCount++;
});
rowCount = rowCount/colCount;
//console.log(rowCount+" rows");
if (rowCount <= 1) {
//Remove hand cursor
$(oTables).find('th').css('cursor', 'default');
//Remove sort arrows
$(oTables).find('th').removeClass('sorting');
}else{
//Add hand cursor
$(oTables).find('th').css('cursor', 'pointer');
//Add sort arrows
$(oTables).find('th').addClass('sorting');
}
}
}
We need to know the row amount...
To achieve this, we first count the column amount and the whole table's td amount.
The row amount is the td amount divided by the column amount.
Based on this number, we can add or remove the sorting class on all th and set the cursor.
Note that when there is no result, there is still one line to show "No matching records found". But since there is only 1 td in this case... divided by the colunm count, we have to think about "one or less line".
;)
Have a look at this CodePen.

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

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>

Change color of a CSS when mouse hover an TD

I'm developing an site with a large table (18 row x 11 columns). To make it easier for who is looking that table, I made it hover an different color for the TR with that:
.responsive tr:hover {
background-color: red;
}
But I want to make the same with the column. But if I use .responsive td:hover {background-color: blue;}, it just hovers the single TD, not the entire column. At least, every TD has the class col1, col2, etc.
How is it possible to change a CSS property when hovering the TD. If this is possible, I can change the background-color from class col1 when I hover the col1 TD.
Any idea?
There is no concept of column in HTML or CSS.
You must use javascript to do that.
Here's a solution using jQuery :
var clean = function(){
$('td').removeClass('colHover');
}
$('td').hover(
function() {
clean();
$('td:nth-child('+($(this).index()+1)+')').addClass('colHover');
}, clean
);
Demonstration
Now, mainly for fun, if you want to handle colspan, you could do that :
var clean = function(){
$('td').removeClass('colHover');
}
$('td').hover(
function() {
clean();
var col = 0;
$(this).prevAll().each(function(){col += parseInt($(this).attr('colspan')||'1')});
$('tr').each(function(){
var c = 0, done = false;
$('td',this).each(function(){
if (c>col && !done) {
$(this).prev().addClass('colHover');
done = true;
}
c += parseInt($(this).attr('colspan')||'1');
});
if (!done) $(this).find('td:last-child').addClass('colHover');
});
}, clean
);
Demonstration

Categories

Resources