0

I have the following select:

<select class="state">
    <option value="1">Done</option>
    <option value="2">Closed</option>
    <option value="2">Open</option>
    <option value="2">Working on it</option>
    <option value="2">Waiting</option>
</select>

The following script is changing the color depending of its content:

$('.state option:selected').each(function(){
    var state = $(this).text();
    if(state == 'Open') {
        $(this).parent().parent().css('background-color', '#e74c3c');
    } else if(state == 'Working on it') {
        $(this).parent().parent().css('background-color', '#f1c40f');
    } else if(state == 'Closed') {
        $(this).parent().parent().css('background-color', '#c0392b');
    } else if(state == 'Waiting') {
        $(this).parent().parent().css('background-color', '#d35400');
    } else if(state == 'Done') {
        $(this).parent().parent().css('background-color', '#27ae60');
    } else {
        $(this).parent().parent().css('background-color', '#bdc3c7');
    }
});
$('select').change(
    function (){
        var color = $('option:selected',this).css('background-color');
        $(this).css('background-color',color);
    }
).change();

But what this script is not doing: It is not changing the color if I change the value of the select. Additionally I am sure, that this code could be much shorter.

The select has a class because this select will appear more than once on a single page.

PhilHarmonie
  • 435
  • 1
  • 6
  • 16

2 Answers2

0

you are not checking the state correctly. you should have:

var state = $('.state option:selected').text()
skend
  • 51
  • 1
  • 9
0
  1. Use addClass and removeClass
  2. Use data-* to set the class to add
  3. Set the style in the class
  4. Remove all class before adding the class of the selected option

$('.state').change(function() {
$(this).parent().parent().removeClass("default done closed open working waiting");
  var state = $("option:selected", this).attr("data-class");
  $(this).parent().parent().addClass(state);

}).change();
.done {
  background-color: #27ae60;
}

.closed {
  background-color: #c0392b;
}

.open {
  background-color: #e74c3c;
}

.working {
  background-color: #f1c40f;
}

.waiting {
  background-color: #d35400;
}

.default {
  background-color: #bdc3c7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <div>
    <select class="state">
    <option value="1" data-class="done">Done</option>
    <option value="2" data-class="closed">Closed</option>
    <option value="2" data-class="open">Open</option>
    <option value="2" data-class="working">Working on it</option>
    <option value="2" data-class="waiting">Waiting</option>
</select>
  </div>
</div>
guradio
  • 15,524
  • 4
  • 36
  • 57