You can go through the options and when the text is the same, select it (explanations in the code):
var texto = 'Mercedes';
// seleciona as options do select
var opts = document.querySelectorAll("select option");
// laço que irá percorrer o select
for(var x=0; x<opts.length; x++){
// verifica se encontrou o texto
if(opts[x].textContent == texto){
// se encontrou, seleciona
document.querySelector("select").value = opts[x].value;
break; // aborta o laço, já encontrou
}
}
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
The .textContent
takes only the text within the element.
With jQuery you can do it in a slightly simpler way by using the .contains () selector. , which goes directly to the element without the need for a loop:
var texto = 'Audi';
$("select option:contains('"+texto+"')")
.prop("selected", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><select><optionvalue="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>