Reputation: 45
I'm trying to change text color depending on the number value.
<?php
$secure_num = 8;
$price_num = 4;
<script>
function change_color_text (num1) {
var rate_num = num1;
if(rate_num >= 7) {
rate_num.style.color = "#008000"; // green
} else if (rate_num >= 4) {
rate_num.style.color = " #FFFF00"; // yellow
} else {
rate_num.style.color = " #FF0000"; // red
}
return rate_num;
}
</script>
<figure class="wp-block-table">
<table>
<thead>
<tr>
<th>Service Rate</th>
<th class="has-text-align-center" data-align="center">Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Secure Rate</td>
<td class="has-text-align-center" data-align="center"><div class="Secure-Rate"><?php echo "<script> change_color_text($secure_num); </script>"?></div></td>
</tr>
<tr>
<td>Price Rate</td>
<td class="has-text-align-center" data-align="center"><div class="Price-Rate"><?php echo "<script> change_color_text($price_num); </script>"?></div></td>
</tr>
</tbody>
</table>
</figure>
?>
So what I'm trying to do is that if $secure_num is 8 then the number '8' (green color) should be echoed, and if $price_num is 4 then the the number '4' (red) should be echoed on the screen. I don't use html format 'cause I'm writing this code on the wordpress theme code(mostly php file).
Upvotes: 0
Views: 763
Reputation: 11
you can write this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="demo"></div>
<script>
function change_color_text (num1) {
var rate_num = num1;
if(rate_num >= 7) {
document.getElementById('demo').innerHTML="green";
document.getElementById('demo').style.color="green";
} else if (rate_num >= 4) {
document.getElementById('demo').innerHTML="yellow"; // yellow
document.getElementById('demo').style.color="yellow";
} else {
document.getElementById('demo').innerHTML="red" // red;
document.getElementById('demo').style.color="red";
}
return rate_num;
}
</script>
</body>
</html>
<?php echo "<script> change_color_text(8) </script>"?>
Upvotes: 1
Reputation: 78
This code will definitely give an error, "cannot read value of undefined"
This has to do with DOM manipulation. In this code, JavaScript engine doesn't understand what element style color you're trying to change.
A way to fix this will be
const rate_num = document.querySelector(".class")
Where .class is the class name of whatever text you're trying to change in the HTML.
Upvotes: 1