How to select an option with value comparison?

Asked

Viewed 345 times

3

I need to do "selected='selected'" in a option whose value is what is saved in the variable state recovered in Ajax. How can I do this?

$('#cep').on("change", function(){
    $.ajax({
        url: 'http://cep.republicavirtual.com.br/web_cep.php',
        type: 'get',
        dataType: 'json',
        crossDomain: true,
        data:{
            cep: $('#cep').val(),
            formato:'json'
        },
        success: function(res){

            res.uf; = "24";
            estado = res.uf;
...

// Estados dentro do select ... 

<select name="estado" id="estado" class="form-control mb-md">
    <option value="">Selecione um estado ...</option>
    <option value="1">Acre</option>
    <option value="2">Alagoas</option>
    <option value="3">Amazonas</option>
    <option value="4">Amapá</option>
    ...

4 answers

4

I usually just change the value (value) and the state is selected automatically, would look like this:

var estado = 3;
$("#estado").val(estado);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="estado" id="estado">
  <option value="">Selecione um estado</option>
  <option value="1">Acre</option>
  <option value="2">Alagoas</option>
  <option value="3">Amazonas</option>
  <option value="4">Amapá</option>
</select>

  • +1, I really liked this answer, it makes a lot of sense to select the option that the value matches, I believe that for those who have a good understanding of select is as readable as going through the elements. if you are actually observing the val() implementation of jQuery it checks if the selector has the value property, and if you have no search for your children, in that it reuses the each that I used in my answer. it turns out that in a matter of performance your does an extra check, but the performance can not even be taken into account, being that it is little thing.

  • @Gabrielrodrigues then, I do not know if it is the best way, but it is very simple and functional and as you said, in this case the performance is not a critical factor so opting for simplicity makes sense.

3


You can make a each in your options selector and check if the value matches your return, and after that add Selected option.

Example:

var valorEstado = 3;

$("#estado option").each(function() {
  if (this.value == valorEstado) {
    $(this).attr('selected', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="estado" id="estado">
  <option value="">Selecione um estado ...</option>
  <option value="1">Acre</option>
  <option value="2">Alagoas</option>
  <option value="3">Amazonas</option>
  <option value="4">Amapá</option>
</select>

2

The most common in these cases is to assign a specific ID or class for each term, which you can reference directly in the answer, type $('#uf'+estado). If not possible you can select the correct option using

// primeiro retira qualquer seleção anterior
$('option').prop('selected', false);
// depois seleciona somente a option com o value correto
$('option[value='+estado+']').prop('selected', true);

1

After you take the state, do it like this:

estado = 3;
$('#estado').find("option[value='"+estado+"']").attr('selected', 'selected');

Browser other questions tagged

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