js select option code example
Example 1: javascript get selected option
var e = document.getElementById("selectElementID");
var value=e.selectElement.options[e.selectedIndex].value;
var text=e.options[e.selectedIndex].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);
}
Example 3: make select option selected javascript
document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected'
Example 4: 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>
Example 5: options in html
<form id="form">
<label for=""></label>
<br>
<input type="" id="">
<br>
<label for=""></label>
<br>
<input list="browsers" name="Thenicknamey" id="Thenickname">
<datalist id="browsers">
<option value=""></option>
<option value=""></option>
<option value=""></option>
</datalist>
<br>
<label for=""></label>
<br>
<input type="" id="">
<br>
<input type="" id="">
</form>
Example 6: javascript option
var s = document.getElementById('s');
var options = [ 'zero', 'one', 'two' ];
options.forEach(function(element, key) {
if (element == 'zero') {
s[s.options.length] = new Option(element, s.options.length, false, false);
}
if (element == 'one') {
s[s.options.length] = new Option(element, s.options.length, true, false);
}
if (element == 'two') {
s[s.options.length] = new Option(element, s.options.length, false, true);
}
});