Michael Michael -4 years ago 130
HTML Question

How the best and fast way to hide option not needed with JavaScript

I have HTML select with several option and i want to hide and show back when needed, as example here my HTML :

<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
<option value="3">D</option>
<option value="4">E</option>
<option value="5">F</option>
<option value="6">G</option>
<option value="7">H</option>

Now i just want to show option E and hide other option. But in other case maybe i want to show all. I know in JavaScript we can hide one option by their value. But i want to know are they best way to hide and show it according performance too (with Javascript)?

Thank you.

Answer Source

You have hidden attribute for that

var myselectoptions=document.getElementById("myselect").options;

function hideoptions(optionObject,optiontohide){
  for (index = 0; index < optiontohide.length; ++index) {

function showoptions(optionObject,optiontoshow){
  for (index = 0; index < optiontoshow.length; ++index) {

hideoptions(myselectoptions, [6,7,8]);      // hide F,G,H
showoptions(myselectoptions, [8]);         // show H
<select id="myselect">
  <option value="0" >Select</option>
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
  <option value="5">E</option>
  <option value="6">F</option>
  <option value="7">G</option>
  <option value="8">H</option>

For support on IE < 11 add this line to css : [hidden] { display: none; }

Jquery can also be used but I think plain Javascript code would be faster as Jquery performs a lot of checks on a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download