TheShinyTuxedo
TheShinyTuxedo

Reputation: 65

Change select css on change value

I am trying to change the background-color depending on the value that is returned by the selected value. I have the following code but I am not getting anywhere:

<script>
$(document).ready(function() {
    $('#assessments').change(function(){
        if ($(this).val() == "0") {
            $('select').css('background-color', '#FF0000');
        } else if ($(this).val() == "1") {
            $('select').css('background-color', '#00FF00');
        } else if ($(this).val() == "2") {
            $('select').css('background-color', '#0000FF');
        }
    });​
});​
</script>

<select id='assessments'>
    <option value='0'>NYC</option>
    <option value='1'>C</option>
    <option value='2'>G</option>
</select>

EDIT: Alrighty besides the DOM ready handler not being there (which I have now added on) the select background-color is still not changing. Am I fetching the value wrong from the select box? Is there a way to output the value so I can check that it is indeed getting the right value or any value at all.

Upvotes: 0

Views: 1471

Answers (1)

adeneo
adeneo

Reputation: 318162

You'll need a DOM ready handler with that, as the script appears before the elements in the DOM.
Also, you'll have to include jQuery to use jQuery methods.

<script>
$(function() {

    $('#assessments').change(function(){
        if ($(this).val() == "0") {
            $('select').css('background-color', '#FF0000');
        } else if ($(this).val() == "1") {
            $('select').css('background-color', '#00FF00');
        } else if ($(this).val() == "2") {
            $('select').css('background-color', '#0000FF');
        }
    });​

});

</script>

<select id='assessments'>
    <option value='0' selected>NYC</option>
    <option value='1'>C</option>
    <option value='2'>G</option>
</select>

Another option would be to move the script to below the elements in the DOM

Upvotes: 5

Related Questions