-1
I have a zip code field where I make a query via javascript, so far so good, is working, in my form I have log field, number, neighborhood (city and state that are selected) I wanted to select the line of select according to this query, I can select but it does not show to the user, I even tried to implement a select fill the other with the state and cities and could not, if anyone can help me at this point I thank you! but follow the code for better understanding.
Selects
<div class="row">
{{--estado--}}
<div class="col-md-4">
<div class="form-group">
<label>UF</label>
<div class="input-group">
<div class="input-group-addon icone-input">
<i class="fa fa-map"></i>
</div>
<select id="parc_uf" name="parc_uf" style="width: 100%">
<option selected value='0'>Selecione um estado</option>
@foreach($estados as $e) @if(Session::get('parc_uf') == $e->id)
<option selected value='{{$e->id}}'>{{$e->uf_sigla}}</option>
@else
<option value='{{$e->id}}'>{{$e->uf_sigla}}</option>
@endif @endforeach
</select>
</div>
</div>
</div>
{{--Cidade--}}
<div class="col-md-8">
<div class="form-group">
<label>Municipio</label>
<div class="input-group">
<div class="input-group-addon icone-input">
<i class="fa fa-map"></i>
</div>
<select id="parc_mun" name="parc_mun" style="width: 100%">
<option value='0'>Selecione um Municipio</option>
@foreach($municipios as $m) @if(Session::get('parc_cidade') == $m->id)
<option selected value='{{$m->id}}'>{{$m->mun_nome}}</option>
@else
<option value='{{$m->id}}'>{{$m->mun_nome}}</option>
@endif @endforeach
</select>
</div>
</div>
</div>
</div>
Java Script
<!-- Adicionando JQuery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Adicionando Javascript -->
<script type="text/javascript" >
$(document).ready(function() {
function limpa_formulário_cep() {
// Limpa valores do formulário de cep.
$("#parc_end").val("");
$("#parc_bairro").val("");
$("#cidade").val("");
$("#uf").val("");
$("#ibge").val("");
}
//Quando o campo cep perde o foco.
$("#parc_cep").blur(function() {
//Nova variável "cep" somente com dígitos.
var cep = $(this).val().replace(/\D/g, '');
//Verifica se campo cep possui valor informado.
if (cep != "") {
//Expressão regular para validar o CEP.
var validacep = /^[0-9]{8}$/;
//Valida o formato do CEP.
if(validacep.test(cep)) {
//Preenche os campos com "..." enquanto consulta webservice.
$("#parc_end").val("...");
$("#bairro").val("...");
$("#cidade").val("...");
$("#uf").val("...");
$("#ibge").val("...");
//Consulta o webservice viacep.com.br/
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {
if (!("erro" in dados)) {
//Atualiza os campos com os valores da consulta.
$("#parc_end").val(dados.logradouro);
$("#parc_bairro").val(dados.bairro);
$("#cidade").val(dados.localidade);
$("#uf").val(dados.uf);
$("#ibge").val(dados.ibge);
var comboCidades = document.getElementById("parc_mun");
var comboEstados = document.getElementById("parc_uf");
var str_cidade = dados.localidade;
var str_uf= dados.uf;
for (var i = 0; i < comboCidades.length; i ++) {
if(comboCidades.options[i].text == str_cidade.toUpperCase()){
comboCidades.options[i].setAttribute("selected", true)
}
}
for (var i = 0; i < comboEstados.length; i ++) {
if(comboEstados.options[i].text == str_uf.toUpperCase()){
comboEstados.options[i].setAttribute("selected", true)
}
}
} //end if.
else {
//CEP pesquisado não foi encontrado.
limpa_formulário_cep();
alert("CEP não encontrado.");
}
});
} //end if.
else {
//cep é inválido.
limpa_formulário_cep();
alert("Formato de CEP inválido.");
}
} //end if.
else {
//cep sem valor, limpa formulário.
limpa_formulário_cep();
}
});
});
</script>
result - You may notice that you are selected but it shows the first option:
two tips: 1) it would be better to compare by "id" instead of "text", 2), use
.setAttribute("selected", "selected")
. See if that solves the problem– Ricardo Pontual
It seems that you are using some library that works with the elements of form(select), it is likely that in the documentation of it there is the explanation of how to set a default value, leaving only as Selected will not work even
– Darlei Fernando Zillmer
The problem is in the two camps, city and state?
– Sam
It really didn’t work, Yes in the two Selects, one is state and the other is city! and since I’m using a library that doesn’t have the same id as mine since it comes from a site search, it’s hard to compare by id!
– Ulisses Gimenes