JQuery val () not working on parameter added via ajax
I have a jQuery / Ajax function that adds 2 <option>
to <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
returns as
<option value="bookA">Book A</option>
<option value="bookB">Book B</option>
and now books
there 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 install selected
option
using .val()
after call addOption()
-
$('#authors').change( function(){
addOption();
$('#books').val('bookB');
});
It doesn't make a choice Book B
.
If I hardcode it .append()
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 options added to a function .ajax
cannot be selected with .val()
, put it if I add them directly?
source to share
This is because the AJAX call is asynchronous, so when you try to select options, it hasn't been added to the selection yet.
Use a callback in a function so you can do something when the response arrives:
function addOption(callback) {
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);
callback();
}
});
}
Using:
$('#authors').change( function(){
addOption(function(){
$('#dropdownB').val('bookB');
});
});
source to share
A JAX is asynchronous , which means that when you call the addOption () method, it can (and probably will) return before the Ajax call is actually made, so you call $('#dropdownB').val('bookB');
before the Ajax callback has been called so that add parameters.
Try putting an $('#dropdownB').val('bookB');
ajax call in your success callback and you can see it works.
source to share
1) You have to put $('#dropdownB').val('bookB');
in the success event of your ajax events because AJAX is asynchronous and your request cannot be completed when you try to change the selected item, so there is no item to select yet.
2) You add to #books
but change the selected item #dropdownB
. They are two different IDs and therefore two different DOM elements.
source to share