Reputation: 133
I have a table that I'm trying to color based on the values in the table. So, if the value in the table is 150%, the cell would be colored red. If the value in the table is 50%, the value would be colored green. However, for some reason, the actual text in the table has a multitude of spaces within them as well as a % symbol. How can I replace any spaces and '%' characters with nothing ('')?
Here is what I have that isn't working:
<script type="text/javascript">
$(document).ready(function () {
$('#myTable td.PercentMem').each(function () {
if ($(this).text().replace(/\s/g, '').replace('%', '') >= '100') {
$(this).css('background-color', '#ff0000');
}
else {
$(this).css('background-color', '#33cc33');
}
});
});
</script>
Thank you!
EDIT
I'm dumb. I forgot to include the fact that these percentages have a decimal point in them. So, what I'm really dealing with is something like "50.89%", and the solutions provided thus far convert that into "5089". How can I keep the decimal?
Upvotes: 2
Views: 95
Reputation: 2910
You can achieve with this, avoid to use jQuery to select elements, use pure JavaScript:
const myCells = document.querySelectorAll('.PercentMem');
myCells.forEach(cell => {
const cellValue = cell.textContent.replace(/\D+/g, '');
cell.classList.toggle(parseInt(cellValue) >= 100 ? 'red' : 'green');
});
Here is the complete fiddler with all the code.
Upvotes: 1
Reputation: 7915
You need to strip out all non-numeric charactes plus convert the resulating string to an int. So something like this: parseInt($(this).text().replace(/\D/g,''))
. Also, in your post you're comparing to a string '100'
, which obviously should be a number. Try this:
$(document).ready(function () {
$('#myTable td.PercentMem').each(function () {
if (parseInt($(this).text().replace(/\D/g,'')) >= 100) {
$(this).css('background-color', '#ff0000');
}
else {
$(this).css('background-color', '#33cc33');
}
});
});
Disclaimer: I have not actually tested this, but this should work.
Upvotes: 2