How to change option from JSON return

Asked

Viewed 91 times

0

How do I change the option below, based on JSON return:

<select name="modalidade-frete" id="modalidade-frete">
    <option value="0">0 - Por conta do emitente</option>
    <option value="1">1 - Por conta do destinatário/remetente</option>
    <option value="2">2 - Por conta de terceiros</option>
    <option value="9" selected>9 - Sem frete</option>
</select>

Note: I wish to remove the value default 9 and change to the value corresponding to the JSON return, for example: data.mod_frete = 1, become so:

<select name="modalidade-frete" id="modalidade-frete">
        <option value="0">0 - Por conta do emitente</option>
        <option value="1" selected>1 - Por conta do destinatário/remetente</option>
        <option value="2">2 - Por conta de terceiros</option>
        <option value="9">9 - Sem frete</option>
</select>

2 answers

2


Just set the value of <select> with the value of the desired option:

var sel = document.getElementById('modalidade-frete');
sel.value = 1; // no caso, sel.value = data.mod_frete 
  • bfavaretto worked in parts. By using the Chrome inspector, the option of value=9 is still selected.

  • 1

    The inspector is showing you the original HTML that the browser received. One thing is the attribute selected (which is in your HTML), and another is the property selected (that you are accessing via JS). The attribute only sets the initial value of the property.

  • I understood, but there’s some way to make that change, even if it’s just "visual"?

  • You can try removeAttribute / setAttribute, but I honestly don’t see any good reason to do it.

1

$.post('destino.php', {data:'data'}, function(response){
  $('#modalidade-frete').val(response.valor_desejado_para_o_option);
}, "json");

[In response to your comment @luccasrodrigo]

$.post('destino.php', {data:'data'}, function(response){
  if($('#modalidade-frete').attr('selected') == true){
    $('#modalidade-frete').attr('selected', 'false'); // Oculta o selected no HTML
  }
}, "json");
  • 1

    Hello Marcelo, I made some small edits in the code, and thank you for the suggestion!

  • Hello again Marcelo, as I already edited the answer and was not included in the issue the selector closure #modalidade-frete, you could even edit it and add the simple quote.

Browser other questions tagged

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