I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined
without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined
initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
3
Answers
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
Then in the jquery, I appended the <select> tag as well:
Now it is working as expected.
:)
Instead of:
you should use:
And in your code:
you missed a quote mark, it should be:
$("#boardingDropdown")
Finally, according to my corrections, it should become:
Try this solution:
The output should be something like this: