0

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>"; ?>
3
  • 1
    The proper way in WordPress to pass variables from PHP to Javascript is to use wp_localize_script() (which requires that you properly enqueue your script first; see wp_enqueue_script() for more on that topic).
    – Pat J
    May 3 at 18:31
  • @PatJ Thanks for the reply. May 4 at 11:54
  • since rate_num is a number, it doesn't have a style property - you should be receiving the error "Cannot set properties of undefined." In any scenario, would it not be easier to simply set the style attribute of the elements using PHP directly?
    – bosco
    May 5 at 23:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.