I'm trying to change text on the table depending on the meta value I give (number).
- if meta value >= 7, number text on table changes to green.
- else if meta value >= 4, number text on table changes to yellow.
- else, number text on table changes to red.
However, this code doesn't work.
<script type="text/javascript">
function change_color_text (num1) {
var rate_num = num1;
if(rate_num >= 7) {
rate_num.style.color = "green"; // green
} else if (rate_num >= 4) {
rate_num.style.color = " yellow"; // yellow
} else {
rate_num.style.color = "red"; // red
}
return rate_num;
}
</script>
<?php $ccf_CAR = get_post_meta( get_the_ID(), 'ccf_CAR', true ); ?> // meta data is number value like 7,2,5 etc. (This code is working)
<?php $ccf_PSC = get_post_meta( get_the_ID(), 'ccf_PSC', true ); ?> // meta data is number value like 7,2,5 etc. (This code is working)
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Rate Subject</th>
<th class="has-text-align-center" data-align="center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Safe Score</td>
<td class="has-text-align-center" data-align="center"><p id="safe_score"><?php echo "<script> change_color_text($ccf_CAR); </script>"; ?></p></td>
</tr>
<tr>
<td>Price Score</td>
<td class="has-text-align-center" data-align="center"><p id="price_score"><?php echo "<script> change_color_text($ccf_PSC); </script>"?></div></td>
</tr>
....same code above for the table
</tbody>
</table>
</figure>
I think there's an error in javascript function or maybe I didn't write properly with this code.
<?php echo "<script> change_color_text($ccf_CAR); </script>"; ?>
wp_localize_script()
(which requires that you properly enqueue your script first; seewp_enqueue_script()
for more on that topic).rate_num
is a number, it doesn't have astyle
property - you should be receiving the error "Cannot set properties of undefined." In any scenario, would it not be easier to simply set thestyle
attribute of the elements using PHP directly?