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

Asked

Viewed 503 times

2

I have a variable

var text that receives predetermined values, and I want the value to select the field item select

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>

Volvo received variable want to be selected Select Volvo.

2 answers

3


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 inside the element.

With jQuery you can make it a little simpler by using the selector .contains(), that goes straight 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>
   <option value="1">Volvo</option>
   <option value="2">Saab</option>
   <option value="3">Mercedes</option>
   <option value="4">Audi</option>
</select>

1

Thus:

JS + Jquery Code

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

Excerpt from the HTML

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.