0

When I add display:none to an <option> tag with JavaScript after the page is ready, it wouldn't hide the default or the selected element, it stays on the hidden option unless I change that manually. The option 08:30 is hidden but it's still there as selected, but not an option. Here is the HTML and there's also a screenshot:

enter image description here

<div class="form-floating mb-3">
    <select class="form-select" id="time">
       <option value="08:30" style="display: none;">08:30</option>
       <option value="08:45">08:45</option>
    </select>
</div>

I've tried disabling the <option> tag as well but it does the same and keeps it selected. I need it to jump into an active select option or any other option but not the one I hide or disable.

Update: I have to use a workaround to get this working. First I've added all <option> tags to the <select> tag, then remove the ones that I don't want:

$('#time').html('
 <option value="08:30">08:30</option>
 <option value="08:45">08:45</option>
 <option value="09:00">09:00</option>
 <option value="09:15">09:15</option>
 <option value="09:30">09:30</option>
 <option value="09:45">09:45</option>
')
$('#time option[value="'09:00'"]').remove()

This works, although doesn't actually solve the issue (I guess that's a bug and hasn't been addressed yet). I would still appreciated an answer to improve the code.

aynber
  • 22,380
  • 8
  • 50
  • 63

1 Answers1

0

Hello & Welcome Mohsen Salehi,

<option hidden>Hidden option</option>

It is not supported by IE < 11.

Please read more about it here How to hide a in a menu with CSS?

Edit:

You can also add disabled to prevent getting selected.

<div class="form-floating mb-3">
<select class="form-select" id="time">
   <option value="08:30" style="display: none;" disabled>08:30</option>
   <option value="08:45">08:45</option>
</select>
</div>
Ketan Kale
  • 31
  • 3
  • Thanks for the reply, but just tested it, still the same. this appears to be a bug. To test it out you can create a ` – Mohsen Salehi May 10 '22 at 01:29
  • @MohsenSalehi Add one default option to the top before ``. – vee May 10 '22 at 02:36
  • @Mohsen Salehi try to add `disabled` as well... E.g. `` – Ketan Kale May 10 '22 at 03:00
  • Thanks @vee and Ketan , this would add an extra option (even though empty or disabled). In our case we'll have to remove multiple options from random positions, so what we need to sort out is how to jump into any other available option other than the disabled/hidden one. Much appreciated! – Mohsen Salehi May 10 '22 at 03:53