Value of a text variable do select a Select item in javascript

2

I have a variable

var text that receives pre-determined values, and I want the value to select the item from the select field

example:

var texto = 'Volvo';



<select>
   <option value="1">Volvo</option>
   <option value="2">Saab</option>
   <option value="3">Mercedes</option>
   <option value="4">Audi</option>
</select>

Variable received Volvo want to select Volvo from Select.

    
asked by anonymous 24.07.2018 / 01:12

2 answers

2

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>
    
24.07.2018 / 02:01
1

This way:

JS + JQuery code

$(document).ready(function() {
    var texto = "Mercedes";
    var exemplo = $("#test").find("option:contains('" + texto + "')");
    exemplo.attr('selected', 'selected');
});

HTML snippet

<select id="test">
   <option value="1">Volvo</option>
   <option value="2">Saab</option>
   <option value="3">Mercedes</option>
   <option value="4">Audi</option>
</select>
    
24.07.2018 / 01:27