html initialize select code example

Example 1: html select default

<select>
  <option value="" selected disabled hidden>Choose here</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
</select>

Example 2: select default value

<option selected>
5
</option>

Example 3: html initialize select

//html
//<select name="sel" id="sel></select>

//js
//generating options
let sel = document.getElementbyID('sel');
let opt = ['option1', 'option2', 'option3'];
for(let idx=0; idx<opt.length; idx++){
  sel.options[idx] = new Option(opt[idx], opt[idx]); //new Option("Text", "Value")
}

//init
for(let idx=0; idx<sel.length; idx++){
  sel.options[idx] = undefined;
}

//generating other options
let opt2 = ['optA', 'optB', 'optC'];
for(let idx=0; idx<opt2.length; idx++){
  sel.options[idx] = new Option(opt2[idx], opt2[idx]);
}

Tags:

Misc Example