Reputation: 1892
I have a dynamically generated select
tag and then after that, I have to make an ajax call to query some values and loop thru it and dynamically generate the options
tag. But for some reason, I cant append an option
tag to my select tag. This is not the issue of asynchronicity right?
const firstElemTd = $('#none td:first-child');
firstElemTd.append(`<select id="the-select"></select>`);
const selectTag = $(`#the-select`);
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option>', {value: balyu.name}).text(balyu.name));
});
}
});
Upvotes: 0
Views: 49
Reputation: 16214
Create the selectTag as a jQuery object first. You can then append to it.
$(function(){
const $firstElemTd = $('#none td:first-child');
const $selectTag = $('<select></select>');
//append the selectTag to the td
$firstElemTd.append($selectTag);
//now that the selectTag is a distinct jQuery object you can append to it. EG:
var response = [{"name":"a"},{"name":"b"},{"name":"c"}];
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});
/* The same thing in the ajax response should work too.
(commented out here for the snippet)
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
$selectTag.append($('<option/>').val(balyu.name).text(balyu.name));
});
}
});
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="none"><tr><td></td></table>
Upvotes: 2
Reputation: 508
You're constructing your $.each incorrectly
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option></option>',
{value: balyu.name,
text: balyu.name}
));
});
}
});
You could also go with another approach:
$.ajax({
method: 'GET',
url: url,
dataType: 'json',
success: function(response) {
$.each(response, function(key, balyu) {
selectTag.append($('<option></option>'
.val(balyu.name)
.text(balyu.name));
});
}
});
Either way will give you what you're looking for.
Upvotes: 1