patternjavascriptMinor
Set same color as prev row if data matches otherwise different color
Viewed 0 times
matchessameotherwisecolordifferentprevrowdataset
Problem
I have a requirement in which I need to set color of two or more rows of a table same if they have same value in cell one and I have to maintain this alternatively i.e. no 3 or 4 rows should have the same color unless there cell value is same.
I have written following code but I don't like it that much as it seems dirty.
Any suggestions?
I have written following code but I don't like it that much as it seems dirty.
function SetGroupingDetails(row, item, color, namedColor) {
$(row)
.css("background-color", color) //set different color for different groups
.addClass(namedColor);
}
$("#tblExport tbody tr").each(function() {
var item = $("td:first", this).text();
var prev = $(this).prev();
if (prev.length > 0) {
var prevItem = prev.find('td:first').text();
if (prevItem == item) {
if (prev.hasClass('Green'))
SetGroupingDetails(this, item, "#009933", "Green");
else
SetGroupingDetails(this, item, "#cc9900", "Orange");
} else {
if (prev.hasClass('Orange'))
SetGroupingDetails(this, item, "#009933", "Green");
else
SetGroupingDetails(this, item, "#cc9900", "Orange");
}
} else
SetGroupingDetails(this, item, "#009933", "Green");
});
#tblExport body {
font: normal medium/1.4 sans-serif;
}
#tblExport {
border-collapse: collapse;
width: 100%;
}
#tblExport th,
td {
padding: 0.25rem;
text-align: left;
border: 1px solid #ccc;
}
#tblExport th {
background: #bfbfbf;
}
Item No.
Item Name
10178601
X
10178601
X
40062595
Y
40062595
Y
80214549
Z
80214549
Z
Any suggestions?
Solution
As previously mentioned,
It is possible to reduce the five calls to
#tblExport body should probably be #tblExport > tbody, and you should trim() text before comparing.It is possible to reduce the five calls to
SetGroupingDetails(). If you don't try to set a background-color manually, then it's a simple matter of adding either a "zebra-even" class or a "zebra-odd" class. Simply toggle between them whenever the text doesn't match its predecessor.var c = 0;
$("#tblExport tbody tr").each(function() {
var $item = $("td:first", this);
var $prev = $(this).prev().find('td:first');
if ($prev.length && $prev.text().trim() != $item.text().trim()) {
c = 1 - c;
}
$(this).addClass(['zebra-even', 'zebra-odd'][c]);
});
#tblExport > tbody {
font: normal medium/1.4 sans-serif;
}
#tblExport {
border-collapse: collapse;
width: 100%;
}
#tblExport th,
td {
padding: 0.25rem;
text-align: left;
border: 1px solid #ccc;
}
#tblExport th {
background: #bfbfbf;
}
#tblExport > tbody > tr.zebra-even {
background-color: #093;
}
#tblExport > tbody > tr.zebra-odd {
background-color: #c90;
}
Item No.
Item Name
10178601
X
10178601
X
40062595
Y
40062595
Y
80214549
Z
80214549
Z
Context
StackExchange Code Review Q#121593, answer score: 2
Revisions (0)
No revisions yet.