javascript select option code example

Example 1: javascript get selected option

var e = document.getElementById("selectElementID");
var value=e.selectElement.options[e.selectedIndex].value;// get selected option value
var text=e.options[e.selectedIndex].text;//get the selected option text

Example 2: javascript get all select options

var options = document.getElementById('mySelectID').options;
for (let i = 0; i < options.length; i++) { 
  console.log(options[i].value);//log the value
}

Example 3: make select option selected javascript

document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'

Example 4: javascript get selected option

let selectElement = document.getElementById("selectElement");
let valueSelected = selectElement.options[selectElement.selectedIndex].value; // get selected option value
var text= selectElement.options[selectElement.selectedIndex].text; //get the selected option text

Example 5: get index of selected option javascript

$("#sel").attr("selectedIndex")
// or
$("#sel")[0].selectedIndex
//or
$(this).prop('selectedIndex')

Example 6: js select option in form

<form name="AddAndEdit">
   <select name="list" id="personlist">
      <option value="P1">Person1</option>
      <option value="P2">Person2</option>
      <option value="P3">Person3</option>
   </select>
</form>