3

Possible Duplicate:
How do I change the background color with Javascript?

I have this javascript function which works fine but I wanted to add to it.

The Risk is calculated by multiplying the severity by the likelihood. The calculation is done by the function below validate_form()

The colour according to values is:

  • Green - less than 6 the input field changed colour to green
  • Orange - between 6 - 9
  • Red - if more than 9

The risk value writes to and input field named "risk1" "risk2" etc.

function validate_form ( ) {
    valid = true; 

    document.calc.risk1.value = document.getElementById('data_1_severity').value*document.getElementById('data_1‌​_likelihood').value;
    document.calc.risk2.value = document.getElementById('data_2_severity').value*document.getElementById('data_2‌​_likelihood').value; 

    return valid;
}

Could someone help me with this? Just want either the risk score to change color depending on value or the background of the cell to change colour - not really bothered. This will show then if the risk is:

  • Green - Low Risk
  • Orange - medium risk
  • Red - high risk.
Community
  • 1
  • 1
php_beginner
  • 47
  • 1
  • 1
  • 5
  • 1
    I assumed you meant to post this as a javascript question and not a PHP one. – Wesley Murch Dec 05 '12 at 16:28
  • You can use conditional statements (`if`), and do a comparison of the values. Then you can create 3 classes in your css, and apply those to the elements depending on the condition. – knownasilya Dec 05 '12 at 16:33

2 Answers2

2

Something like this:

var changeColor = function(obj){

  if(obj.value < 6){
    obj.style.backgroundColor = 'green';
  } else if(obj.value >= 6 && obj.value <= 9){
    obj.style.backgroundColor = 'orange';
  } else if(obj.value > 9){
    obj.style.backgroundColor = 'red';
  }

};

Then inside your validate_form() function:

changeColor(document.calc.risk1);

Even better would be to create CSS classes for each color and do something like:

obj.className = 'green';

instead of

obj.style.backgroundColor = 'green';
Freddie
  • 691
  • 2
  • 9
  • 23
1

you can do this using jQuery

your CSS should look like this:

.low-risk{
    background: green;
}

.medium-risk{
    background: orange;
}

.high-risk{
    background: red;
}

and here is a javascript function for changing the color:

<script>
    function changeInputColor(input, value){
        $(input).removeClass();
        if (value < 6){
            $(input).addClass('low-risk');
        }
        else if(value >= 6 && value <= 9){
            $(input).addClass('medium-risk');
        }
        else{
            $(input).addClass('high-risk');
        }
    }
</script>
Johny
  • 183
  • 5