0

I am creating a form for a client where, if User selects 'Other' in the dropdown Select menu, a text box will appear. It should remin hidden otherwise. I've seen this in many sites.

I can do this easily for Radio Buttons using something like this code:

.the-text-input-box {
  opacity: 0;
}

input[type="radio"]:checked ~ .the-text-input-box {
  opacity: 1;
}

...But I have no idea how to target the 'Other' option in a Selector in the same way.

I'm hoping to achieve this using only CSS.

Reverend2100
  • 810
  • 1
  • 7
  • 17
  • Likely duplicate of [CSS selector for select option value](http://stackoverflow.com/questions/16452634/css-selector-for-select-option-value) – mplungjan Mar 20 '15 at 15:56
  • I think is not possible in full CSS, because you can test option element but is contained in select element and CSS does not go back to the parent element for use sibling selector – Bluety Mar 20 '15 at 16:03

1 Answers1

1

You can't do this only with CSS. You'll need Javascript because the selected option of your select is not a sibling of your input-box in the DOM :

<select name="mySelect" id="mySelect">
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="other">Other</option>
</select>
<input type="text" name="input-box" id="inputBox" cols="30" rows="10" class="hidden"/>

With a checkbox it's possible because the input-box directly follow your box :

<input type="checkbox" name="checkme" id="checkme"/>
<input type="text" name="myInput" id="myInput" />

So in Javascript, you'll need an event listener on your select to hide/show the input-box. Something like this should do the trick : http://jsfiddle.net/1cevh233/

JS

var selectEl = document.getElementById('mySelect');
var inputBox = document.getElementById('inputBox');
var listener = function(e){
if(selectEl.value == "other"){
       inputBox.className="";
}else{
       inputBox.className="hidden";
}
}


selectEl.addEventListener('change',listener);

CSS

.hidden{
    display:none;
}
ylerjen
  • 4,109
  • 2
  • 25
  • 43