Phoenix Logan
Phoenix Logan

Reputation: 1258

CSS - Hide elements (class) based on value of select box

I have a <select> box in a <form>, and when its value is other, I want elements that have the class .applicableSupportCase to be hidden. I am trying to do this with just CSS. What am I doing wrong?

CSS

.applicableSupportCase  {
  transition: transform 0.3s ease, opacity 0.3s ease;
}
#typeBox[value="other"] ~ .applicableSupportCase{
  opacity: 0;
  transform: scaleY(0);
}

HTML

<select class="contactField" id="typeBox">
  <option value="supportCase" selected="selected">Support case</option>
  <option value="other">Other</option>
</select>

<label class="applicableSupportCase">Device:</label>

There are more elements with the applicableSupportCase class, but you get the point.

Upvotes: 2

Views: 6595

Answers (3)

Enigmadan
Enigmadan

Reputation: 3408

This can't be done using a <select> item, however because of the pseudo class :checked states of checkboxes and radio buttons, you can accomplish what you wanted using those instead:

HTML

<input type="radio" id="supportCase" name="radios"> 
<label for="supportCase">Support Case</label>
<input type="radio" id="other" name="radios"> 
<label for="other">Other</label>
    <br />
<label class="applicableSupportCase">Device:</label>

CSS

input[id=other]:checked ~ .applicableSupportCase {
  visibility:hidden;
}

I used visibility, but you can change the attribute to whatever you want.

If you want an ease in and out, then create the same statement using the :not(:checked) pseudo class:

input[id=other]:not(:checked) ~ .applicableSupportCase {
  //whatever ease(out) you want here
}

JSFiddle: http://jsfiddle.net/ja2ud1Lf/

Upvotes: 3

Doug
Doug

Reputation: 23

I would use personally create another class for hidden objects (eg 'hiddenClass'), and use jquery similar to the following:

$( "#typeBox" ).change(function(){
 if($("#typeBox").val()=="other")
 {
     $(".applicableSupportCase").each(function(){
         $(this).addClass("hiddenClass");
     });
 }
});

Upvotes: 0

LcSalazar
LcSalazar

Reputation: 16841

Actually, the css attribute selector don't look at value in the way that you are thinking...

Though Javascript sees the value property as the selected option's value, CSS sees only the markup, and an select[value='something'] attribute selector would actually look for this:

<select value='something'>

Not for the <option> selected.

Through css-only you will not be able to change another element using the selected option because the <option> is nested to the <select> tag, and there's no parent navigation selection on css.

EDIT

You can, however, mock it up with javascript, and leave your css selector as it is. Just trigger the select's onchange event to set an attribute called value to the DOM select element:

See Working Fiddle Example

document.getElementById('typeBox').onchange = function() {
    this.setAttribute('value', this.value);
};

Upvotes: 5

Related Questions