<table>
<thead>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
</thead>
</table>
.red {
background-color: red;
}
.green {
background-color: green;
}
How can i make automatically add class red and green for TR with jQuery?
LIVE EXAMPLE: http://jsfiddle.net/2Htwx/
$('tr:odd').addClass('red');
$('tr:even').addClass('green');
Assuming you want every other row red or green, as per your JS-fiddle. Note that this is within each table, so you won't see red/green/red across ALL table rows.
If you want that, try this:
var oddFilter = function(index) {
console.log(index);
return (index % 2) == 1;
},
evenFilter = function(index) {
console.log(index);
return (index % 2) == 0;
}
$('tr').filter(oddFilter).addClass('red').end()
.filter(evenFilter).addClass('green');
Note that <thead>, <tfoot> etc can still mess up the display, since that moves rows around the display.
You don't need JavaScript to accomplish this 'table-striping' effect. Use of the CSS nth-child selector will do the trick
thead tr {
background: green; /* Set all tr elements to green */
}
thead tr:nth-child(even) {
background: red; /* Override the colour for just the even ones */
}
Note: This selector is not supported in older browsers. IE8 and down.
Further reading on CSS nth-child:
http://css-tricks.com/how-nth-child-works/
You mean like this?
$(document).ready(function() {
var class = "";
$("tr").each(function(idx, elem) {
class = (idx % 2 == 0)?"red":"green";
$(elem).addClass(class);
});
});
Could you please explain "automatically"?
You mean at page ready event?
Maybe somthing like this:
$(document).ready(function (){
$("tr:odd").css("background-color", "#f00");
$("tr:even").css("background-color", "#0f0");
});
Here's the simplest method:
$("tr").addClass("red");
try this
var trs = jQuery('tr');
trs.filter(':even').addClass('red');
trs.filter(':odd').addClass('green');
to not selecting two-times every tr
Related
I have an html table and I want to color the rows based on the value in the first column of that row. If the value is "CONFIRMED" I want to color the row green, and if it is "UNCONFIRMED" I want to color the row red.
The JS I am using to do this is:
$(function(){
$("tr").each(function(){
var col_val = $(this).find("td:eq(1)").text();
if (col_val == "CONFIRMED"){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});
The CSS looks like this:
.selected {
background-color: green;
color: #FFF;
}
.bad {
background-color: red;
color: #FFF;
}
The html table is generated from a pandas dataframe in my Django view and passed in like this:
<div class="table-responsive" style="margin-left: 15%; margin-right: 15%; overflow:auto;">
{{ datatable | safe }}
</div>
The problem is that it's coloring all of my rows red. Can anyone tell me what I'm doing wrong?
Since you use ==="CONFIRMED" make sure it's really: UPPERCASE, and that there's no leading or ending spaces " CONFIRMED" or "CONFIRMED " in the HTML.
The code you're showing will color .selected the entire row whos :eq(1) TD has the "CONFIRMED" content:
$(function(){
$("tr").each(function(){
var col_val = $(this).find("td:eq(1)").text();
if (col_val == "CONFIRMED"){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});
.selected{
background-color:green;
}
.bad{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td><td>CONFIRMED</td>
</tr>
<tr>
<td>2</td><td>UNCONFIRMED</td>
</tr>
</table>
nothing bad about it.
if that's not what you see on your screen note that :eq() is index based, and elements index start at 0 so :eq(0) is probably what you want?
Another probable thing is that you don't have the exact content string set as "CONFIRMED" but probably there's some spaces before or after - so make sure to trim them using $.trim()
if( $.trim(col_val) === "CONFIRMED" )
if you additionally want to make your code even more flexible about the UPPERCASE or Capitalization you can do as:
if( $.trim(col_val.toLowerCase() ) === "confirmed" )
// Will work on "CONFIRMED", "Confirmed", "conFIRMed" etc
<style>
tr[data-stat="confirmed"]{
background-color: green;
color: #fff;
}
tr[data-stat="unconfirmed"]{
background-color: red;
color: #fff;
}
</style>
<table>
<tr data-stat="confirmed">
<td>1</td>
<td>Confirmed</td>
<td>bla.. bla.. bla..</td>
</tr>
<tr data-stat="unconfirmed">
<td>2</td>
<td>Not Confirmed</td>
<td>bla.. bla.. bla..</td>
</tr>
</table>
To find the first column in a row, you want to use the first-child selector. You can iterate over every first column with the each function.
We then look at the text and then add the appropriate class to the column's parent (tr).
$(document).ready(function() {
$("td:first-child").each(function() {
if ($(this).text() === "Confirmed") {
$(this).parent().addClass("green");
}
else {
$(this).parent().addClass("red");
}
});
});
http://jsfiddle.net/cw43ejjf/
If you are looking for the first column in the row you want to use:
var col_val = $(this).find("td:eq(0)").text();
Change the td:eq(1) to td:eq(0)
In this example http://jsfiddle.net/bYAK4/ why does hiding a cell cause the whole column to shift over and what can I do to avoid this?
HTML
<table>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Hello</td>
<td><div class="hide">World</div></td>
</tr>
</table>
CSS
table {
width:400px;
}
JS
$(document).ready(function() {
$('.hide').slideUp();
});
Try with
$(document).ready(function() {
$('.hide').hide();
});
slideUp may causes the meshup and also give width to td like
table tr td{
width:200px;
}
See this DEMO
See this using slideUp DEMO2
Because you're essentially removing it from the dom, but not destroying it.
If you only want to hide it use:
$(document).ready(function() {
$('.hide').css('visibility', 'hidden');
});
It looks like jQuery is animating the width of the td, in either .slideUp() or even if you use .hide(1000).
Try adding width to the td instead of the table:
td { width: 200px; }
See fiddle. I added a border around the td so you can see what happens.
I tried to change the color of the first td element in each row to red.
HTML:
<table id="test">
<tr>
<td>test1</td>
<td>test2</td>
</tr>
<tr>
<td>test3</td>
<td>test4</td>
</tr>
</table>
I tried this JS:
var tr = document.getElementsByTagName('tr');
tr.firstChild.style.color = 'red';
No Jquery please.
Use rows and cells to access the rows and columns of the table. See below code,
var table = document.getElementById('test');
for (var i = 0; i < table.rows.length; i++) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.color = 'red'; // or anything you want to do with first col
}
DEMO: http://jsfiddle.net/QNEyx/
Parsing with JS could be costly, if you are fine achieving the same with the CSS, then here you go.
#test tr td:nth-of-type(1) {
color: red;
}
Or
#test tr td:first-child {
color: red;
}
As said in another reply, css is the natural way to accomplish this.
As you are stuck with js, you can use js to inject a stylesheet in your page:
var styleNode=document.createElement("style");
document.head.appendChild(styleNode);
var cssString="#test tr td:first-child {color: red;}";
if (styleNode.styleSheet) { // IE
styleNode.styleSheet.cssText = cssString;
}
else {
styleNode.appendChild(document.createTextNode(cssString));
}
The benefit of using a stylesheet is that you avoid race conditions (case when the table is built dynamically).
By using disabled attribute on an input is possible to prevent user input and trigger a slightly different look.
Here is the demo http://jsfiddle.net/D2RLR/3023/
Let's suppose I want to apply the same style to a different TAG like a table.
In fact, I am using handsontable to generate an Excel-like data grid editor.
How can I apply disabled attribute in the following context (TAG like a table)?
Here is the demo using handsontable and bootstrap http://jsfiddle.net/D2RLR/3025/
You can't apply Bootstrap's existing input[disabled] styling, but you can add new CSS that mimics the styles exactly.
For example:
#exampleGrid td {
cursor: not-allowed;
background-color: #EEE;
color: #9E9999;
}
Obviously this doesn't include your readonly logic, and looks a little weird with your fiddle (because the column and row headers are the same color), but that's the gist of it.
Check here:
http://handsontable.com/demo/conditional.html
There is .readOnly cell property - use it!
HTML inputs also have readonly property, not only disabled property, an there are some considerable differences between their behaviour.
Boostrap is only styling the inputs based on their disabled attribute like:
input[disabled], select[disabled], textarea[disabled], input[readonly], select[readonly], textarea[readonly] {
background-color: #EEEEEE;
cursor: not-allowed;
}
So you won't be able to use bootstrap to do that, because tables don't have such attribute.
You should use a plugin of sorts or roll your own.
Maybe this can help... changes the look of the cell and you can edit on it.
HTML
<table class="editableTable">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>E-mail</th>
<th>Telephone</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>João Carlos</td>
<td>joca#email.com</td>
<td>(21) 9999-8888</td>
</tr>
<tr>
<td>002</td>
<td>Maria Silva</td>
<td>mariasilva#mail.com</td>
<td>(81) 8787-8686</td>
</tr>
<tr>
<td>003</td>
<td>José Pedro</td>
<td>zepedro#meuemail.com</td>
<td>(84) 3232-3232</td>
</tr>
</tbody>
</table>
CSS
* {
font-family: Consolas;
}
.editableTable {
border: solid 1px;
width: 100%
}
.editableTable td {
border: solid 1px;
}
.editableTable .editingCell {
padding: 0;
}
.editableTable .editingCell input[type=text] {
width: 100%;
border: 0;
background-color: rgb(255,253,210);
}
JS
$(function () {
$("td").dblclick(function () {
var originalContent = $(this).text();
$(this).addClass("editingCell");
$(this).html("<input type='text' value='" + originalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("editingCell");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(originalContent);
$(this).parent().removeClass("editingCell");
});
});
});
I have to change colors for alternative rows. one row in "Green" and another one is in "Yellow".
<tr class="ms-viewheader" vAlign="top">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
I have to skip "ms-viewheader" row and start coloring next sibling. Full row should be in
color.
How to do this?
run something like this in javascript
// define the background color for even and odd rows
var bgColors = {
even: '#eaeaea',
odd: '#aeaeae'
};
$("table tr:not(.ms-viewheader):even").css({"backgroundColor":bgColors.even});
$("table tr:not(.ms-viewheader):odd").css({"backgroundColor":bgColors.odd});
Ok, so you want to just handle this one table. Try this:
$("table[class='ms-listviewtable'] tr[class='']").css("background-color","yellow");
$("table[class='ms-listviewtable'] tr:.ms-alternating").css("background-color","green")
I am assuming that the table has a class, otherwise you could add a class to it to differentiate it.
Demo:
http://jsfiddle.net/J7dVX/13/
Does it have to use JS? Here's a CSS solution.
http://jsfiddle.net/HvLRs/1/
CSS:
tr:nth-child(2n) {
background-color:green;
}
tr:nth-child(4n) {
background-color:yellow;
}
HTML:
<table id="alternating">
<th class="ms-viewheader" vAlign="top"><td>Header</td></th>
<tr class=""><td>1</td></tr>
<tr class="ms-alternating"><td>2</td></tr>
<tr class=""><td>3</td></tr>
<tr class="ms-alternating"><td>4</td></tr>
<tr class=""><td>5</td></tr>
<tr class="ms-alternating"><td>6</td></tr>
<tr class=""><td>7</td></tr>
<tr class="ms-alternating"><td>8</td></tr>
</table>
If you must use jQuery, I modified Teddy's code: http://jsfiddle.net/HvLRs/3/
$("table tr:.ms-alternating:even").css("background-color","yellow");
$("table tr:.ms-alternating:odd").css("background-color","green");
If you want to treat ms-viewheader the same as ms-alternating:
$('tr:not([class^="ms"])').css('background-color','red');
$('tr[class^="ms"]').css('background-color','blue');
otherwise, if you just want to skip ms-viewheader and start alternating all the other rows:
$('tr:not([class^="ms"])').css('background-color','red');
$('tr.ms-alternating').css('background-color','blue');
Proof of concept: http://jsfiddle.net/daybreaker/J7dVX/
If you need to do it dynamically, use:
$("tr[class='']").css("background-color", "green");
$(".ms-alternating").css("background-color", "yellow");
As an alternative you could also use:
$(".ms-viewheader").siblings().css("background-color", "green");
$(".ms-alternating").css("background-color", "yellow");
Something like this - use modulus
for row, i in $('tbody tr')
color = if i % 2 is 0 then '#ff0000' else '#00ff00'
$(row).css 'background-color', color
I see in your latest comment on the original question that the ms-alternating class is already there in the markup for you??
If so, you shouldn't need any jquery or fancy CSS3 rules to do this. You can do this with regular ol' CSS.
Just add this to your CSS:
tr td {
background-color:green; /* this colors the whole table green */
}
tr.ms-viewheader td {
background-color:transparent; /* we don't want the header to get any color, so reset it */
}
tr.ms-alternating td {
background-color:yellow; /* and finally, color the alternating rows yellow */
}
Please note, this will color all tables on the page. You probably only want to target a single table. So you need some more specific selectors. Does the table you want to color have an ID or class on it you could target?
Good luck!