When you select the first field, the second value changes. But when you first open the page, in the second field, it should be the default only "Select model", and I display all the values. After I choose the second or third, everything gets better. What is the glitch? Even selected added does not help.

<select name="first" id="first"> <option value="one" selected>Выберите марку</option> <option value="two">BMW</option> <option value="tri">Audi</option> </select> <select name="second" id="second"> <option value="one" class="one" selected>Выберите модель</option> <option value="two" class="two">Второй 1</option> <option value="two" class="two">Второй 2</option> <option value="two" class="two">Второй 3</option> <option value="tri" class="tri">третий</option> <option value="tri" class="tri">третий 2</option> </select> <script> $('#first').change(function(){ var cls = $(this).val(); $('#second option').hide(); $('#second ' + '.' + cls).show(); }); </script> 
  • one
    I do not think that a glitch, at you hide occurs only after change of the first. - olegatro
  • <style>.two { display: none; } .tri { display: none; }</style> <style>.two { display: none; } .tri { display: none; }</style> - Igor

1 answer 1

You need the option from the second select not to display when the page loads. There are several ways to do this.

Using CSS

We do not display all options except the selected one.

 #second option:not([selected]) { display: none; } 


Using HTML

Add to each option attribute style="display: none"

 <select name="second" id="second"> <option value="one" class="one" selected>Выберите модель</option> <option value="two" class="two" style="display: none">Второй 1</option> <option value="two" class="two" style="display: none">Второй 2</option> <option value="two" class="two" style="display: none">Второй 3</option> <option value="tri" class="tri" style="display: none">третий</option> <option value="tri" class="tri" style="display: none">третий 2</option> </select> 


Using jQuery

Hide option on readiness of document object model

 $(document).ready(function() { $('#second option:not([selected])').hide(); });