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 ?
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.