简体   繁体   中英

Changing output text colour when positive / negative

I have a simple bit of jQuery below which is working as expected. I would however like to change it so if the number is positive it turns green and if it is negative it turns red. I know the CSS part and so the styling isn't an issue. I am just unsure how to add the class depending on the result.

<script type="text/javascript">
jQuery(function($) {
    $("#cost_price").on("keyup",function() {
        var totalcost= $("#_regular_price").val() - $(this).val() 
        $(".total_cost").html(totalcost);
    })
})
</script>

您可以使用三元语句:

totalcost < 0 ? $(".total_cost").addClass("negative") : $(".total_cost").addClass("positive")

It should be as simple as:

var $totalCost = $(".total_cost");

if(totalCost < 0) {
   $totalCost.removeClass("green").addClass("red");
} else {
   $totalCost.removeClass("red").addClass("green");
}

$totalCost.html(totalCost);

you have a .negative class that sets it to red then Javascript applies it or not

$("#cost_price").on("keyup",function(){
  var totalcost= $("#_regular_price").val() - $(this).val() 
  $(".total_cost").html(totalcost);
  if(totalcost < 0) $(this).addClass("negative");
  else $(this).removeClass("negative");
});

One approach:

$(".total_cost").html(totalcost).addClass(Math.abs(totalCost) === totalCost ? 'positive' : 'negative');

Simple JS Fiddle demo .

References:

if(totalcost >= 0){
    if($(".total_cost").hasClass('red')
        $(".total_cost").removeClass('red');
    if(!$(".total_cost").hasClass('green')
        $(".total_cost").addClass('green');
}
else{
    if($(".total_cost").hasClass('green')
        $(".total_cost").removeClass('green');
    if(!$(".total_cost").hasClass('red')
        $(".total_cost").addClass('red');
}

one simple way is to use css3's attrib matching, and a tiny bit of js to publish the value property to a real attribute :

 <style> input[alt^='-'] { color: red; } </style>
 <input oninput="this.alt=this.value"  />

which shows red if the value starts with "-". you can use a type=number and min/max attribs to further improve the user interface.

tested in chrome, ff, and IE9. use onkeyup for IE8 compat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM