I have a jQuery/Ajax function that is appending 2 <option>s to a <select>.
function addOption() {
var author = $("#authors").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$.ajax({
type: "post",
url: "books.php",
data: { author:author },
success: function(response){
$('#books').append(response);
}
});
}
response comes back as –
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
and now books is –
<select id="books">
<option value="">Please Select</option>
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
</select>
This works great.
Now I want to set the selected option using .val() after calling addOption() –
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
This does not make Book B selected.
If I hard code the .append() it works –
function addOption() {
var author = $("#author").val();
$('#books').empty();
$('#books').html('<option value="">Please Select</option>');
$('#books').append('<option value="bookA">Book A</option>\n<option value="bookB">Book B</option>);
}
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
Is there a reason why my option(s) appended in the .ajax function cannot be selected using .val(), put it can if I append them directly?
That’s because the AJAX call is asynchronous, so when you try to select the options, it hasn’t been added to the select yet.
Use a callback in the function, so that you can do something when the response has arrived:
Usage: