Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to select another Element based on a HTML Select Option Value

Is there a CSS selector that allows me to select an element based on an HTML select option value?

<select>     <option value="1">1</option>     <option value="2">2</option>     <option value="3">3</option> </select>  <p>Display only if an option with value 1 is selected</p> 

I'm looking for an HTML/CSS only method to only display a selected number of form fields. I already know how to do it with Javascript.

Is there a way to do this?


Edit:

The question title is perhaps misleading. I'm not trying to style the select box, that's pretty common and plenty of answers on SO already. I'm was actually trying to style the <P> element based on the value selected in the <select>.

How ever what I'm really trying to do is to display a number of form fields based on a selected numeric value:

<select name="number-of-stuffs">     <option value="1">1</option>     <option value="2">2</option>     <option value="3">3</option> </select> <div class="stuff-1">      <input type="text" name="stuff-1-detail">      <input type="text" name="stuff-1-detail2"> </div> <div class="stuff-2" style="display:none">       <input type="text" name="stuff-2-detail">      <input type="text" name="stuff-2-detail2"> </div> <div class="stuff-3" style="display:none">      <input type="text" name="stuff-3-detail">      <input type="text" name="stuff-4-detail2"> </div> 

I would like to display div.stuff-1 and div.stuff-2 when number-of-stuffs=2 and display div.stuff-1 div.stuff-2 and div.stuff-3 when number of stuffs=2.

Something like this fiddle

like image 1000
hannson Avatar asked May 09 '13 00:05

hannson


People also ask

How do I select HTML element in CSS?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

How do I style a selection dropdown in CSS?

There are many ways to design a <select> dropdown menu using CSS. The Dropdown Menu is mainly used to select an element from the list of elements. Each menu option can be defined by an <option> element that can nested inside the <select> element.


2 Answers

Its called an attribute selector

option[value="1"] {   background-color:yellow; }  

Example http://jsfiddle.net/JchE5/

like image 84
Kevin Bowersox Avatar answered Oct 03 '22 01:10

Kevin Bowersox


You can use

select option[value="1"]

but browser support won't be fantastic.

like image 44
adnrw Avatar answered Oct 03 '22 01:10

adnrw