How to change an attribute of a select without option value?

Asked

Viewed 105 times

-1

I have a select rendered in view with recovered data in a database. In the table in question estado, have the attributes id, siglaEstado and descricaoEstado. In case I’m using the id in the value of option to make changes to the bank, as in the code:

<div class="form-group col-md-4">
   <label for="estado"><span>*</span>Estado:</label>
   <select id="estado" class="form-control" name="estado" required>
       <option selected>Selecione seu estado</option>
       <?php foreach($estados as $estado){?>
           <!-- Tentei adicionar esse data-uf para renderizar a opção -->
           <option data-uf="<?php echo $estado['siglaEstado'];?>" 
              value="<?php echo $estado['idEstado'];?>"> 
              <?php echo $estado['descricaoEstado'];?> 
           </option>
        <?php }?>
   </select> 
</div>

And I have a script that automatically fills in the address according to the zip code, where the api returns a json containing the state UF.

$("#cep").focusout(function(){
    $.ajax({
        url: 'https://viacep.com.br/ws/'+$(this).val()+'/json/unicode/',
        dataType: 'json',
        success: function(resposta){
            $("#logradouro").val(resposta.logradouro);
            $("#complemento").val(resposta.complemento);
            $("#bairro").val(resposta.bairro);
            $("#cidade").val(resposta.localidade);
            //Aqui eu tentei recuperar o valor no data-attr inserido no html
            $("#estado").data("data-uf").val(resposta.uf);
            $("#numero").focus();
        }
    });
});

I tried to put a data- option but could not fill the state.

How do I fill this select according to this acronym returned in the api without having to change the value of my option?

1 answer

1


You can select the option that contains the data-Uf equal to the answer and make it Selected. Try:

$("#estado option[data-uf="+resposta.uf+"]").attr("selected", true);

  • It worked, thank you very much!

Browser other questions tagged

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