Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text colour depending on positive or negative integer

I have this very simple calculator which I have written in JavaScript. Basically it works out the profit between two integers with the tax amount being 5%.

I would like the output (#result) to change colour depending if the result number is either a positive or negative integer.

Here is my calculator's HTML:

Buying Price
<br /><br />
<input id="buying" type="text">
<br /><br />
Selling Price               
<br /><br />
<input id="selling" type="text">
<br /><br />
<input type="submit" onclick="output();">
<p id="result" name="r1"></p>

Here is my calculator's JS:

function output(){
    var buying = document.getElementById('buying').value;
    var selling = document.getElementById('selling').value;

    parseInt(selling) / 20;

    document.getElementById('result').innerHTML =  parseInt(selling) - parseInt(buying) - parseInt(selling) / 20;
}

Here is a JS fiddle: http://jsfiddle.net/ac81ee78/

I have attempted using jQuery for this however it did not work.

Please if anyone could help me with this it would be greatly appreciated.

like image 382
Bradley Cousins Avatar asked Sep 23 '15 18:09

Bradley Cousins


1 Answers

I modified your code a bit so it changes color based on the sign of the output. jQuery isn't needed for this - we can use plain JS functions to change the color of the output box.

Live Demo:

var resultEl = document.getElementById('result');

function output() {
    var buying = document.getElementById('buying').value;
    var selling = document.getElementById('selling').value;
    var resultVal = parseInt(selling) - parseInt(buying) - parseInt(selling) / 20;
    resultEl.innerHTML = resultVal
    if (resultVal >= 0) {
        resultEl.style.color = "green";
    } else {
        resultEl.style.color = "red";
    }
}
Buying Price
<br />
<br />
<input id="buying" type="text">
<br />
<br />Selling Price
<br />
<br />
<input id="selling" type="text">
<br />
<br />
<input type="submit" onclick="output();">
<p id="result" name="r1"></p>

JSFiddle Version: http://jsfiddle.net/ac81ee78/2/

like image 173
Maximillian Laumeister Avatar answered Sep 30 '22 07:09

Maximillian Laumeister