To do this you will have to pick up the specific elements using document.getElementsByName("cores")[0].getElementsByTagName('option')
or document.querySelectorAll('select[name=cores] option')
Then you will have to iterate in loop, because both functions return "lists" of elements, in case will return the options, in DOM the property to "mark" an OPTION element as selected is the <elemento>.selected=true
to unmark is <elemento>.selected=false
In case you want the Options with value=2 and value=3 to be selected, then just check in each element if they are the values you want:
var opcoes = document.getElementsByName("cores")[0].getElementsByTagName('option');
// poderia ser também
// var opcoes = document.querySelectorAll('select[name=cores] option');
function seleciona()
{
for (var i = 0, j = opcoes.length; i < j; i++) {
if (opcoes[i].value == "2" || opcoes[i].value == "3") {
opcoes[i].selected = true;
} else {
opcoes[i].selected = false;
}
}
}
<form action="/action_page.php">
<label for="cars">Escolha uma ou mais cores:</label>
<select name="cores" multiple readonly>
<option value="1">Amarelo</option>
<option value="2">Vermelho</option>
<option value="3">Verde</option>
<option value="4">Azul</option>
</select>
<br><br>
<button type="button" onclick="seleciona()">selecionar</button>
</form>
Note that I did it very explicitly and using if only to explain (to make it easy to understand the logic), but you can make it simpler like this:
for (var i = 0, j = opcoes.length; i < j; i++) {
opcoes[i].selected = opcoes[i].value == "2" || opcoes[i].value == "3";
}
If it is 2 or 3 true arrow, otherwise false arrow
Now if you have specific values coming from another source you can use you can put them in an array to say that these should be the values marked, thus:
var valoresDeOutraFonte = [2, 3];
for (var i = 0, j = opcoes.length; i < j; i++) {
opcoes[i].selected = valoresDeOutraFonte.indexOf(opcoes[i].value) !== -1;
}
The .indexOf()
fetch on array valoresDeOutraFonte
the current option value in the loop, if it is present returns 0 or a larger number, if it is not present returns -1. There is also the function .includes()
, could do so:
var valoresDeOutraFonte = [2, 3];
for (var i = 0, j = opcoes.length; i < j; i++) {
opcoes[i].selected = valoresDeOutraFonte.includes(opcoes[i].value);
}
But if you need to run on older browsers, as an old Android is likely to include no support