Jonathan Griffin Jonathan Griffin - 5 months ago 27
Javascript Question

JQuery conditional formatting based on hidden field

I came by a script by @Stofke (original jsfiddle) for using JQuery for conditional formatting on a HTML Table.

I have been trying to tweak this script so that the score is based on a hidden form field (see below), but when I do, I only get one colour showing, rather than than the different colour scales.

$(function() {
$('tr> td').each(function(index) {
var scale = [['vPoor', 10], ['poor', 50], ['avg', 250], ['good', 1250], ['vGood', 6250]];
var score = $('input.sf').val();
for (var i = 0; i < scale.length; i++) {
if (score <= scale[i][1]) {
$('input.sf').closest('tr').addClass(scale[i][0]);
}
}
});
});


I am sure it is a rookie error, but if someone could please point the error out to me that would be great.

HTML table structure

<table>
<col id="name" />
<col id="score" />
<thead>
<tr>
<th>Name</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>Allan, Paul</td>
<td><input type="hidden" class="sf" value="5"></td>
</tr>
<tr>
<td>Bartlett, James</td>
<td><input type="hidden" class="sf" value="60"></td>
</tr>
<tr>
<td>Callow, Simon</td>
<td><input type="hidden" class="sf" value="35"></td>
</tr>
<tr>
<td>Dennis, Mark</td>
<td><input type="hidden" class="sf" value="289"></td>
</tr>
<tr>
<td>Ennals, Simon</td>
<td><input type="hidden" class="sf" value="1020"></td>
</tr>
<tr>
<td>Finnegan, Seamus</td>
<td><input type="hidden" class="sf" value="5648"></td>
</tr>
</tbody>
</table>

Answer

Your first and main issue is with the following line:

var score = $('input.sf').val();

That gets the value of the first <input> element with the class "sf". I assume you have such an element for each row. You need to get the one in the row, not the first one.

Something like the following might work, but it assumes the <input> element is a descendant of the <td> element. If that is not correct, you might need to change it a bit.

var score = $(this).find('input.sf').val();
Comments