The first option hidden in SELECT only works for the first selection, not for all

advertisements

I have an issue with some code. Basically I want to remove the first option from <select> using jQuery, which is working, but only for the very first select. If I have 3 dropdowns the code works only for the first one. I tried to use .each but to be honest I don't really know where and will this even help. This is a html:

      <select class="checkb" name="gender">
     <option disabled value="">Gender</option>
     <option value="male">Male</option>
     <option value="female">Female</option>
  </select>  

  <select class="checkb" name="age">
     <option disabled value="">Age</option>
     <option value="under 13">Under 13</option>
     <option value="13-17">13-17</option>
     <option value="18-24">18-24</option>
     <option value="25-44">25-44</option>
     <option value="45-64">45-64</option>
     <option value="65+">65+</option>
  </select>  

  <select class="checkb" name="cinema">
     <option disabled value="">Select your cinema</option>
     <option value="001">Cinema 1</option>
     <option value="002">Cinema 2</option>
     <option value="003">Cinema 3</option>
  </select>

and this is jquery:

    $(".checkb option:first").attr('hidden','hidden');

It perfectly hides the 'Gender' text, but doesn't hide 'Age' and 'Select your cinema'.

Thank you in advance.


That selector will select the first <option> element it finds that's within an element with the class .checkb, which is why it's only removing the first <option> from the first <select>.

You could instead use the :nth-child() selector to get all <option> elements that are the first child of the <select> with that class:

$('.checkb option:nth-child(1)').attr('hidden', 'hidden');

Edit: I was curious about the efficiency of three approaches to solving this (the two suggested in the current answers, as well as a third that's a variation of Christopher Kenney's answer) so decided to test it. You can see the results here.