52488

Jquery - Change span text color based on numeric value

Question:

I'm trying to build a review system in WP with Advanced Custom Fields, but I can't solve this. I want to change the color of a score based on the number. For example: if the writer puts 0-40 as score it has to be changed to red; if the writer puts 40-60 it has to be changed to orange; if the writter puts 60-80 it has to be green...

HTML:

<div class="r-summary"> <span id="score"> <?php the_field('score'); ?> */HERE GOES THE NUMBER WITH THE SCORE </span> </div>

Answer1:

Fiddle: <a href="http://jsfiddle.net/5zdemo3j/" rel="nofollow">http://jsfiddle.net/5zdemo3j/</a>

(change the score in the HTML section and "Run" to see changes)

$(function () { // Score Color var score = parseInt($('#score').text().trim()); var color = 'red'; if (!isNaN(score)) { if (score >= 40) { color = 'orange'; } if (score >= 60) { color = 'green'; } $('#score').css('color', color); } });

Answer2:

Use this function in document.ready state if you are loading the score with PHP so the span will be edited when the document is loaded:

<pre class="snippet-code-js lang-js prettyprint-override">$(document).ready(function() { var score = parseInt($("#score").text()); if (score <= 40) { $('#score').css('color', 'red'); } else if (score > 40 && score <= 60) { $('#score').css('color', 'orange'); } else if (score > 60) { $('#score').css('color', 'green'); } }); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="r-summary"> <span id="score"> 50 </span> </div>

I used 50 as a score example here, and you can change it and see the results.

You will proceed like this:

<ul><li>Get the score from the span.</li> <li>According to the score value, change the color of the span.</li> </ul>

Answer3:

Something like this may work as well.

<?php function the_field() { return htmlspecialchars('40-60'); } ?> <html> <head> <style> .red { background: red; } .orange { background: orange; } .green { background: green; } </style> </head> <body> <div class="r-summary"> <span id="score"> <?php echo the_field('score'); ?> </span> </div> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script> $(function(){ var $span = $('.r-summary').find('#score'); var score = $span.text().trim(); console.log(score); switch(score) { case '0-40': $span.addClass('red'); break; case '40-60': $span.addClass('orange'); break; case '60-80': $span.addClass('green'); break; } }); </script> </body> </html>

Answer4:

This is the solution.

HTML:

<pre class="snippet-code-html lang-html prettyprint-override"><div class="r-summary"> <span id="score"> 75 <!--Value Printed by PHP--> </span> </div>

jQuery:

<pre class="snippet-code-js lang-js prettyprint-override">$(document).ready(function(){ var score = $('#score').text(); if (score >= 0 && score <= 40) { $('#score').css('background-color','red'); } else if (score > 41 && score <= 60) { $('#score').css('background-color','orange'); } else if (score > 61 && score <= 80) { $('#score').css('background-color','green'); $('#score').css('color','white'); } });

Check out this <a href="https://jsfiddle.net/byvn9yuL/" rel="nofollow">fiddle</a>!

Answer5:

try the below code

<!DOCTYPE html> <html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script> $(document).ready(function(){ var score = parseInt($("#score").text(),10); if(score >= 0 && score < 40){ $("#score").removeClass().addClass("redScore"); }else if(score >= 40 && score < 60){ $("#score").removeClass().addClass("orangeScore"); }else if(score >= 60 && score < 80){ $("#score").removeClass().addClass("greenScore"); } }); </script> <style> .redScore{ color: #FF0000; } .orangeScore{ color: #FF9933; } .greenScore{ color: #33CC33; } </style> </head> <body> <div class="r-summary"> <span id="score"> 70 </span> </div> </body> </html>

Answer6:

If you want to do it with native JS.

(function () { var scoreSpan = document.getElementById("score"), score = parseInt(scoreSpan.innerHTML); if (score != NaN) { if (score >= 0 && score <= 40) { scoreSpan.style.color = 'red'; } else if (score > 40 && score <= 60) { scoreSpan.style.color = 'orange'; } else if (score > 60 && score <= 80) { scoreSpan.style.color = 'green'; } else { scoreSpan.style.color = 'black'; // or whatever you want as default } } }());

<a href="http://jsfiddle.net/evrim/tmy74u46/" rel="nofollow">http://jsfiddle.net/evrim/tmy74u46/</a>

Recommend

  • jquery-ui sortable on divs with TinyMCE editors causes text to disappear
  • Show post if true/false is yes. Advanced custom fields
  • How can I order by a variable in this PHP code?
  • Post loop in category filter not working
  • How do i do the following curl command in Java
  • Failed to read schema document 'http://www.springframework.org/schema/tool/spring-tool-4.1.xsd&
  • Aptana 3 remove bundle (jquery)
  • How do I retrieve the user information of a user authenticated with Apache's mod_ldap?
  • Uncaught TypeError: $(…).select2 is not a function
  • Bad request using file_get_contents for PUT request in PHP
  • Refering to the class itself from within a class mehod in Objective C
  • Get data from AJAX - How to
  • C++ Partial template specialization - design simplification
  • ImageMagick, replace semi-transparent white with opaque white
  • Is there a javascript serializer for JSON.Net?
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Problems to linebreak with an int in JLabel
  • How reduce the height of an mschart by breaking up the y-axis
  • Get object from AWS S3 as a stream
  • Why doesn't :active or :focus work on text links in webkit? (safari & chrome)
  • Cross-Platform Protobuf Serialization
  • SSO with signing and signature validation doesn't work
  • Validaiting emails with Net.Mail MailAddress
  • Where to put my custom functions in Wordpress?
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • Upload files with Ajax and Jquery
  • ORA-29908: missing primary invocation for ancillary operator
  • Do I've to free mysql result after storing it?
  • SVN: Merging two branches together
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • A cron job substitute?
  • json Serialization in asp
  • Buffer size for converting unsigned long to string
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • Android Google Maps API OnLocationChanged only called once
  • Binding checkboxes to object values in AngularJs
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?