If you can, with ES6...
function setOption(selectElement, value) {
return [...selectElement.options].some((option, index) => {
if (option.value == value) {
selectElement.selectedIndex = index;
return true;
}
});
}
...otherwise...
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('my-select'), 'b');
See it!
If it returns false
, then the value could not be found :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…