Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda