Reputation: 63
I have a selectbox, which's content and itself get changed with ajax. I want to change the content with ajax, after it loaded, I want to change the selected option as "test_type". When I get the data with ajax and change the #type_select_div's content with the new selectbox, it gets loaded, I can see the options but, selected option can't be changed by jquery. (you'll see as test2 below) But instead of using ajax, if I give the content (which is exactly same with the ajax response), it works perfectly. (you'll see as test1 below)
I couldn't find what I am doing wrong.
HTML part:
<div id="type_select_div">
<select id="formElementTypeName" name="formElementTypeName" class="form-control ">
</select>
</div>
<button onclick="loadAndChange()">load and change</button>
javascript part:
function loadTypes(){
/* test1: works */
var msg='<select class="form-control" name="formElementTypeName" id="formElementTypeName">'
+'<option value="type1">type1</option>'
+'<option value="test_type">test_type</option>'
+'</select>';
$('#type_select_div').html(msg);
/* end of test1*/
/* test2: doesn't work */
$.ajax({
type: "POST",
url: "ajax_actions.php",
success: function(msg){
$('#type_select_div').html(msg);
}
});
/* end of test2 */
}
function loadAndChange(){
$.when(loadTypes()).done(function () {
$('select[name="formElementTypeName"]').find('option[value="test_type"]').attr("selected",true)
});
}
Upvotes: 0
Views: 672
Reputation: 78565
You need to return the result of the $.ajax
call to your method so that jQuery knows it is a promise:
function loadTypes(){
return $.ajax({
type: "POST",
url: "ajax_actions.php",
success: function(msg){
$('#type_select_div').html(msg);
}
});
}
function loadAndChange(){
$.when(loadTypes()).done(function () {
$('select[name="formElementTypeName"]').find('option[value="test_type"]').attr("selected",true)
});
}
Upvotes: 2
Reputation: 781888
You need to return the Deferred
from loadTypes()
:
function loadTypes(){
var msg='<select class="form-control" name="formElementTypeName" id="formElementTypeName">'
+'<option value="type1">type1</option>'
+'<option value="test_type">test_type</option>'
+'</select>';
$('#type_select_div').html(msg);
return $.ajax({
type: "POST",
url: "ajax_actions.php",
success: function(msg){
$('#type_select_div').html(msg);
}
});
}
Upvotes: 2