How to select a value comparison option?

3

I need to make "selected='selected'" in option whose value is what is written to the state variable retrieved 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>
    ...
    
asked by anonymous 20.10.2016 / 13:37

4 answers

3

You can make a each in your options selector and check if the value hits your return, and after that add the 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><selectname="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>
    
20.10.2016 / 13:45
4

I usually just change the value and the state is automatically selected, it 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><selectname="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>
    
20.10.2016 / 13:48
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 response, type $('#uf'+estado) . If it is 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);
    
20.10.2016 / 13:54
1

Once you get the status, do so:

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