0

I have a selectbox and inside options below,

<select id="car_brands">
  <option style="color: red">BMW</option>
  <option style="color: red">Mercedes</option>
  <option>Toyota</option>
  <option>Nissan</option>
  <option style="color: red">Honda</option>
</select>

I want to get an alert message in jquery, "this car's model is BMW, etc.." when I click red ones. If I click other I don't want to see any alert message on the screen. Thanks in advance

Mara Black
  • 1,666
  • 18
  • 23
Bos
  • 33
  • 3
  • Sidepoint: style should be end with semikolon `style="color: red;"` – Maximilian Fixl Jan 10 '20 at 12:09
  • This [answer (how-to-style-the-option-of-an-html-select-element)](https://stackoverflow.com/questions/7208786/how-to-style-the-option-of-an-html-select-element) may helps you – Maximilian Fixl Jan 10 '20 at 12:11
  • 1
    @MaximilianFixl - `;` in CSS is a **separator**, not a terminator; [details](https://www.w3.org/TR/css-syntax-3/#syntax-description). It's absolutely fine and normal not to have them in the above. – T.J. Crowder Jan 10 '20 at 12:13
  • Dear @MaximilianFixl thanks I checked the link but I couldn't see a solution. – Bos Jan 10 '20 at 12:17

2 Answers2

2

Get the current selection and check if the color is red with crt.style.color

function getSelected(optionSelected) {
  const crt = optionSelected.options[optionSelected.selectedIndex]
  if (crt.style.color === "red") {
    alert("This car's model is " + crt.text)
  }
}
<select id="car_brands" onChange="getSelected(this);">
  <option style="color: red">BMW</option>
  <option style="color: red">Mercedes</option>
  <option>Toyota</option>
  <option>Nissan</option>
  <option style="color: red">Honda</option>
</select>
Mara Black
  • 1,666
  • 18
  • 23
0
var selectedCar = $('#car_brands').find(":selected");

if(selectedCar[0].style.color == "red"){
  console.log(`Selected car is ${selectedCar.text()}`)
}

most basic way I can think of. Can be made even simpler given time.

Ali Beyit
  • 431
  • 1
  • 6
  • 19