Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
How do I select value based on value received from api in jQuery?

I have select function that that will shows the selected value based on the API.

value read from API

 "status": "success",
    "result": {
        "fruit_id": 5,
        "fruit_name": Orange,
    }
<select class="form-control mb-3" id="selectFruit">
   <option value="99" hidden> Fruit</option>
   <option value="3">Apple</option>
   <option value="5">Orange</option>
</select>

This is what I have tried

const getKnowledgeID = (sId) =>{
        axios.get(`${api}bsl?id=${sId}`)
        .then(function(res){
            //console.log(res);
            if(res.data.status =='success'){
               
                a = res.data.result;

                let cat_type ='';

                if(a.fruit_id == 5){
                    cat_type += `   <select class="form-control mb-3" id="selectFruit">
                                        <option value="99" hidden> Fruit</option>
                                        <option value="3">Apple</option>
                                        <option value="5" selected>Orange</option>
                                    </select>
                                `;
                }
                else{
                    cat_type += ` <select class="form-control mb-3" id="selectFruit">
                                        <option value="99" hidden> Fruit</option>
                                        <option value="3" selected>Apple</option>
                                        <option value="5">Orange</option>
                                    </select>`;
                }


                $('#fruit').append(` 
                          <div class="col-lg-12 md-mb-50">
                                <div class="form-group row">
                                    <div class="col-lg-4">
                                        <label class="form-label"> Fruit Category</label>
                                       ${cat_type}
                                    </div>
                                </div>
                            </div>
                `);
            }
        });
    }

I believe that this is not a good solution on how to show the selected value. What if I have more that 5 <option> I don't want to keep repeating the same thing. How do I improve this method to make it more simpler ? How do I show the id = 5 is the selected value based on the API value ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The quick way to achieve what you require is to add the select element with nothing selected. Then you can set its val() based on the fruit_id in the response:

const getKnowledgeID = (sId) => {
  axios.get(`${api}bsl?id=${sId}`).then(function(res) {
    if (res.data.status == 'success') {
      $('#fruit').append(`<div class="col-lg-12 md-mb-50"><div class="form-group row"><div class="col-lg-4"><label class="form-label"> Fruit Category</label><select class="form-control mb-3" id="selectFruit"><option value="99" hidden> Fruit</option><option value="3">Apple</option><option value="5">Orange</option></select></div></div></div>`);                              
      $('#selectFruit').val(res.data.result.fruit_id);                          
    }
  });
}

However the most optimal solution would be to have all that HTML already present in the DOM when the page loads, hidden if necessary. When the response is received from your AJAX call, show the content and then set val() on it instead. This method is preferred because it removes the HTML code from the JS; ideally there should be as little mixing of the scripts as possible.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda