I am creating a table looks like this with the codes below:
I am trying to use 'Javascript' to do set condition and compare to value in "td". I am having problem to set different condition for each column.
Eg: I want to set 2 conditions, how do i assign td name/id?
[Condition 2] Highlight, if 'percentage' less than '80%'.
<style>
table, th, td {
border: 1px solid black;
}
</style>
<script src="js/jquery.min.js"></script>
<table id='ss'>
<tr>
<th>WW</th>
<th>Qty</th>
<th>percentage</th>
</tr>
<tr>
<td>WW01</td>
<td>1000</td>
<td>50%</td>
</tr>
<tr>
<td>WW02</td>
<td>2000</td>
<td>90%</td>
</tr>
</table>
<script>
$("#ss td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue <=1000)) {
thisCell.css("background-color","#FFEEC4");
}
}
)
</script>
Check my Snippet, based from your example condition:
Eg: I want to set 2 conditions, how do i assign td name/id?
- [Condition 1] Highlight, if 'Qty' less than '1000'.
- [Condition 2] Highlight, if 'percentage' less than '80%'.
$('#ss tr').each(function() {
var that = $(this);
var c1 = $('td:nth-child(2)', that);
var c2 = $('td:nth-child(3)', that);
if (parseInt(c1.text()) < 1000)
c1.css('background-color', '#FFEEC4');
if (parseInt(c2.text()) < 80)
c2.css('background-color', '#FFEEC4');
});
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='ss'>
<tr>
<th>WW</th>
<th>Qty</th>
<th>percentage</th>
</tr>
<tr>
<td>WW01</td>
<td>1000</td>
<td>50%</td>
</tr>
<tr>
<td>WW02</td>
<td>2000</td>
<td>90%</td>
</tr>
</table>
Check for the index of the table column and then apply the condition.
$("#ss tr").each( function(i, ele) {
$(ele).find('td').each(function(index, v) {
var cellValue = parseInt($(v).text());
console.log(cellValue);
if (!isNaN(cellValue) && (((cellValue <=1000) &&(index == 1)) || ((cellValue <=80) &&(index == 2)))) {
$(v).css("background-color","#FFEEC4");
}
})
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<script src="js/jquery.min.js"></script>
<table id='ss'>
<tr>
<th>WW</th>
<th>Qty</th>
<th>percentage</th>
</tr>
<tr>
<td>WW01</td>
<td>1000</td>
<td>50%</td>
</tr>
<tr>
<td>WW02</td>
<td>2000</td>
<td>90%</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With