Mehdi Bouhalassa
Mehdi Bouhalassa

Reputation: 195

Change color on select > option change

I'm trying some very basic stuff, but I can't get my head around it...

Very simple, but I'm going circle: I want the background of the BODY in my page to change to orange when the OPTION with the RESET text associated with it is selected.

If it's a number (1, 2 or 3), the background becomes white.

Here's my code: http://jsfiddle.net/PQW88/2/

$( document ).ready(function() {

    var reset = $('option:selected').text();

    if (reset === 'reset') {
        $('body').css('background-color', 'orange');
    }
    else {
        $('body').css('background-color', 'white');
    }

});

Can't seem to target it correctly since it's always orange, without any errors...

THANKS IN ADVANCE!!!

Upvotes: 1

Views: 887

Answers (2)

Felix
Felix

Reputation: 38102

You need to use change() event to detect whenever your select value has been changed:

$( document ).ready(function() {

    $('select').on('change',function() {
        var reset = $('option:selected').text();
        if (reset === 'reset') {
            $('body').css('background-color', 'orange');
        }
        else {
            $('body').css('background-color', 'white');
        }
    });

});

Updated Demo

Upvotes: 2

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

You have not used this:

$('select').change(function () {
  var reset = $('option:selected').text();
  if (reset === 'reset') {
    $('body').css('background-color', 'orange');
  } else {
    $('body').css('background-color', 'white');
  }
}

All you needed was select and its change event. Then the function would go on.

Upvotes: 2

Related Questions