lechnerio
lechnerio

Reputation: 982

jQuery change text of select depending on selected value

I'm trying to change the text color of the selection box depending on the selected value.

it's working, kind of. Is there a way to not apply the css to the entire element and only to the selection box itself?

https://i.sstatic.net/Z928f.jpg when I apply the gray color all of the elements get gray. Is it possible that only the "( keine )" is gray when the selection box is collapsed?

$('select').on('change load', function(){
// console.log($(this).children("option:selected").val());
  if($(this).children("option:selected").val() == "keine"){
    $(this).css('color', '#BFBFBD');
  } else {
    $(this).css('color', '#000');
  }
});

$('select').trigger('change');

HMTL Code:

<select>
  <option value="keine">( keine )</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

https://jsfiddle.net/1keyup/bfd74h5k/1/

Upvotes: 0

Views: 160

Answers (1)

Sergey
Sergey

Reputation: 5476

You can get the selected value and check if it equals 'keine'. Then apply gray color:

$('select').on('change', function(){
  const value = $(this).val();
  if(value === 'keine') {
    // apply glay color
  } else {
    // apply default color
  }
});

Demo(It's just a quick sample, can be refactored of course:))

Upvotes: 1

Related Questions