jQuery and css: hide/show select options with a certain css class

Viewed 26205

In the html code I have select options like this:

  <option value="1" class="myclass5">Value1</option>

In jQuery:

var cod = $(this).val(); // This is the value of another select: when the value 
$("option[class^=myclass]").hide();
$("option[class^=myclass]").each(function () {
    $("option[class^=myclass" + cod + "]").show();
});

EDIT

I have two select. When I select a value in the first select, the second one must be populated accordingly (I have to prevent an ajax call).

I put all the second select values in a session var, but my problem is in selecting only those ones tied to the first select, so I was trying through css classes.

EDIT2

<select name="firstselect">
   <option value="0" selected="selected">Choose...</option>
   <option value="1">Value1</option>
   <option value="2">Value2</option>
   <option value="3">Value3</option>
</select>

<select name="secondselect">
   <option value="0" selected="selected">Choose...</option>
   <option value="myclass1">Value11</option>
   <option value="myclass1">Value12</option>
   <option value="myclass1">Value13</option>
   <option value="myclass2">Value21</option>
   <option value="myclass2">Value22</option>
   <option value="myclass2">Value23</option>
   <option value="myclass3">Value31</option>
   <option value="myclass3">Value32</option>
   <option value="myclass3">Value33</option>
</select>

EDIT3

For me greenish's solution is good, but there is an issue on IE that I don't succeed in explaining: when I use the back button, the user selected value is "lost", that is, if I log on the console the user selected value, I see its "index" in the new cloned select. In the html source code, there is the whole original select.

EDIT4

I resolved thanks to this post

https://forum.jquery.com/topic/jquery-select-box-selectedindex-problems-in-internet-explorer-ie-on-refresh-and-back-buttons

5 Answers
Related