set select option to Selected with value coming from a JSON

Asked

Viewed 102 times

0

Good afternoon friends! I have a modal with a city edit form that carries data coming from a JSON. Everything works. The problem now is that mine does not select the correct state. My JSON returns the state ID that I assign to an Hidden input. I do not know how to put this value in . Can help me ?

<div class="col-md-12">
                        <input hidden id="hdIdCidade"/>
                        <input hidden id="hdEstado"/>
                        <select name="estados" id="estados" class="form-control" style="width:400px;">              
                            <?php
                            $select = $conexao->prepare("SELECT * FROM estados ORDER BY nome ASC");
                            $select->execute();
                            $fetchAll = $select->fetchAll();
                            foreach ($fetchAll as $estados) {
                                echo '<option value="' . $estados['id'] . '">' . $estados['nome'] . '</option>';
                            }
                            ?>      
                        </select>
                    </div>

inserir a descrição da imagem aqui

  • I’ll try here Gabriel. Thank you very much.

1 answer

0


If you have the status id within the Hidden input you can make a comparison between its value and what you have within the select. with the code below I took the options and stored in the states variable, then I took the Hidden input and assigned a value, which would be the id you have, then I made a foreach comparing the values, when it finds the option with the same input value it changes the option attribute to Selected.

let estados = document.querySelectorAll("select option");
let idEstadoEl = document.querySelector("input#hdEstado");

let json = {"id": 3}
idEstadoEl.value = json.id;

estados.forEach(estado => {

            if(estado.value == idEstadoEl.value){
                estado.selected = true;
            }

});
  • Gabriel gave right! Thanks a lot brother. God bless you!

Browser other questions tagged

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