简体   繁体   中英

Change css based in Select option value selected

I have in one form, one selects with one question that if determined value selected I need to display none the next question. How can I make a jquery code that detects that the user selected a determinated option in select and change the CSS of the page?

<select>
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="mercedes">Mercedes</option>
   <option value="audi">Audi</option>
</select>

Your question is a bit vague, but i think this is what your after:

 const value = $('#selectID option[value=""]').prop("selected", true);

 if (value....") {
     // do css stuff
 }

Additionally you can get the value / text like so:

<select id="car_manufacturer">
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="mercedes">Mercedes</option>
   <option value="audi">Audi</option>
</select>

<script>
   const element = document.getElementById("car_manufacturer");
   const value = element.options[element.selectedIndex].value;
   const text = element.options[element.selectedIndex].text;
 </script>

You could extend on the above with a on onchange event on the select element.

<select id="car_manufacturer" onchange="selectManufacturer(this)">

Manipulate CSS:

JavaScript:

document.body.style.backgroundColor = "red";

jQuery:

$("body").css("background-color","red");

Fiddle

onchange example with css manipulation:

http://jsfiddle.net/9L0czmeq/

So as far as I understand with your short description you need to do something based on the value selected by user in select box which we call an event onchange.I am writing a code example for you

<select onchange="somefunction($(this).val())">
 <option value="1">Option 1</option>
 <option value="2">Option 2</option>
 </select>

<script>
  function somefunction(value){
     if(value == 1){
      $("body").css("background-color","red");
     }
     if(value == 2){
       $("body").css("background-color","yellow");
     }
  }
   </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM