create element in javascript option code example
Example 1: javascript add option element to select
javascript add option/element to select:
const newOpt = document.getElementById('option-input');
let mySelect = document.getElementById('mySelect');
const opts = Object.values(mySelect.options);
const option = document.createElement('option');
optValues = opts.map(opt => opt.value.toLowerCase());
if(optValues.indexOf(newOpt.value.toLowerCase()) !== -1){
newOpt.nextElementSibling.after("Category exists");
}else{
option.value = newOpt.value;
option.text = newOpt.value;
mySelect.add(option);
mySelect.value = option.value;
}
Example 2: 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);
}
});