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>
...
+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.
– Gabriel Rodrigues
@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.
– Sergio Barros