How to select the result of a CEP json in an existing option?

Asked

Viewed 211 times

0

$.getJSON(url, function(json){

    $("#pf_endereco").val(json.logradouro);
    $("#pf_bairro").val(json.bairro);
    $("#cidade").val(json.localidade); <----
    $("#estado").val(json.uf); <----

How to put the information of locality and Uf as shown in these arrows (<----) inside a form when it’s of the type select > option?

Updating

json.localidade - "MS"
json.localidade - "Campo Grande"

<option value=""></option>
<option value="000001">AC</option>
<option value="000002">AL</option>
<option value="000003">AM</option>
<option value="000004">AP</option>

Update 2

inserir a descrição da imagem aqui

  • Here are possible methods. http://stackoverflow.com/questions/740195/adding-options-to-a-select-using-jquery-javascript

  • 1

    You want to create new options or mark an existing one as selected?

  • Mark an existing one as selected !!!

  • How are the values of your options? And what comes in json.locality and . Uf?

  • bfavaretto I updated the question with the two information - the feedback and options.

  • The ideal would be to return 000001 etc in json.Uf instead of MS. And the city equivalent.

  • Unfortunately it is an external script and returns the data this way. Probably having to select by text !!!

Show 2 more comments

1 answer

2


If you have no way to change what comes in JSON to hit with your values, you need a selector that looks at the content of options, not its value:

$("#estado option:contains('" + json.uf + "')").prop('selected', true);
$("#cidade option:contains('" + json.localidade + "')").prop('selected', true);
  • Returning where?

  • 1

    But it’s supposed to be an object. (hint: use console.log instead of Alert, and always open your browser console). What’s in $("#estado option:contains('" + json.uf + "')").length?

  • For the information returned on Update 2 I think you’re only having a problem selecting the fields because you’re returning the required data.

  • Try $('#estado').val($("option:contains('" + json.uf + "')").val())

  • No !!! http://encomenda.axitech.com.br/sys/cadastro

  • use what is in my answer and then $('#estado').trigger("chosen:updated");. You do not have a normal select, you are using a plugin called Chosen.

Show 1 more comment

Browser other questions tagged

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