Change select's class based on selected option's class

Posted by Alasdair on Stack Overflow See other posts from Stack Overflow or by Alasdair
Published on 2010-01-14T10:43:34Z Indexed on 2010/04/03 15:03 UTC
Read the original article Hit count: 345

Filed under:
|
|
|

I have a page that contains numerous <select> elements. What I'm trying to achieve is to ensure that if a <select>'s selected <option> has a class called italic, then the <select> then has the italic class added (i.e. jQuery.addClass('italic')). If it doesn't, then the italic class is removed from the <select> to ensure other <option> elements are displayed correctly (i.e. jQuery.removeClass('italic')).

What I'm noticing with most of my attempts is that either all the <select> have the italic class or that the italic class isn't being removed accordingly.

Since I'm unsure my choice in selectors and callback logic are particularly sound or good practice in this instance (as I've been frustratingly trying to make it work) I've decided not to include the code I used in previous attempts. Instead, refer to this small HTML & CSS example:

.italic {
    font-style: italic;
}

<select id="foo" name="foo" size="1">
  <option value="NA" selected="selected"> - Select - </option>
  <option value="1">Bar</option>
  <option value="2">Fu</option>
  <option value="3">Baz</option>
</select>

Also, I am aware that not all browsers support CSS styling of <select> and <option>. The related J2EE web application will only ever be accessed via Firefox under a controlled environment.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about html