select <select> item by value
If you are using jQuery (1.6 or greater)
$('#x option[value="5"]').prop('selected', true)
If someone looking for jquery solution, use the val()
function.
$("#select").val(valueToBeSelected);
In Javascript,
document.getElementById("select").value = valueToBeSelected;
Using Javascript:
document.getElementById('drpSelectSourceLibrary').value = 'Seven';
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 :)