Reputation: 860
I want to update a select options according to date that the user picks. For that I tried using ajax request to get data and append the data received to a select element as options. There's nothing wrong with the json object that's received as I tried logging data to console and it gives the data I ant. But hen I try to append it to select element the options do not get appended.
JavaScript code
$.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
html code
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
Upvotes: 0
Views: 361
Reputation: 1099
function f1(){ $.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
}
var data ={
"sessions" : [{"value":"value 1","text":"Option 1"},
{"value":"value 2","text":"Option 2"},
{"value":"value 3","text":"Option 3"},
{"value":"value 4","text":"Option 4"},
{"value":"value 5","text":"Option 5"}]
}
function fillSelect(){
var sessionList=data.sessions;
$('#session12').empty();
var msg='';
console.log(sessionList.length);
for(i=0;i<sessionList.length;i++){
var bean=sessionList[i];
msg+='<option value="'+bean.value+'">'+bean.text+'</option>';
}
$('#session12').html(msg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session12" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<button type="button" onclick="fillSelect()"> click to fill</button>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
</div>
If response of async request you are getting in data
is similar to what i have written in data variable in snippet then my way of generating the option
will work just fine. If response you are getting is exactly same as i have shown in data(by that i mean structure of the variable) then you can simply replace all your code in ajax
function with my code in fillSelect
function
Upvotes: 2