Ad

Jquery Function To Change Text Color Depending On A Special Character

- 1 answer

I want to change the text color if there's a negative number in my HTML list

This is my call to my jquery function inside my HTML.

<ul id="negativeValidation">
    <li>123.5</li>
    <li>-43.5</li>
</ul>

This is my jquery function:

$(document).ready(function() {

    $('#negativeValidation', function() {

        if($("li:contains('-')")== true)
        {
            $("li").css("color", "red");
            console.log("True");
        }else{
            $("li").css("color", "green");
            console.log("False");
        }

    });

});

It's not working, when I go to the console I alway get the "false" message so I would like to know what's wrong or if I'm missing something.

Ad

Answer

First you have console.log('False') in both cases.

write it like this JS Fiddle

$(document).ready(function() {

  $('#negativeValidation li').each(function() {
    var txt = $(this).text();

    if (txt.indexOf('-') > -1) {
      $(this).css("color", "red");
      console.log("True");
    } else {
      $(this).css("color", "green");
      console.log("False");
    }

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="negativeValidation">
  <li>123.5</li>
  <li>-43.5</li>
</ul>

Ad
source: stackoverflow.com
Ad