So I came across this and thought I'd offer a couple of solutions.
The easiest way for a single select, is just to set the value of the select:
var mySelect = document.getElementById( 'my-select-id' );
mySelect.value = 7;
You can also get the selected option by value just the same way:
console.log( mySelect.value );
What I was looking for was a better way to set the values of a multiselect (<select multiple>...</select>
) but as it turns out - it seems you have to loop through the options, and set them in some kind of for
loop:
function setMultiSelectValues( select, values ) {
for (var i = 0; i < select.options.length; i++) {
var option = select.options[i];
if ( values.includes( option.value ) ) {
option.selected = true;
}
}
}
And then use it like:
var mySelect = document.getElementById( 'my-select-id' );
var myValues = [ 'option-1', 'option-5' ];
setMultiSelect( mySelect , values );
Demo: https://codepen.io/rmorse/pen/QWNymdb
$('#x').val('5');
. – Protagoras