I'm getting predefined values, which i have to insert into two selects:
<div id="wrapper">
<select id="first">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="second"></select>
</div>
Options inside #second depends on selected value in #first. This options are loaded via ajax:
$('#first').change( function() {
$.ajax({
url: "giveMeValues.phpOrWhatever"
}).done(function() {
// just simulating data from ajax call
$('#second').append(
'<option value="a">a</option>'+
'<option value="b">b</option>'+
'<option value="c">c</option>'
);
});
});
The problem is, I can set value of #second after ajax data will be loaded. So following code will of course not work:
$('#first').val('2').change();
$('#second').val('b').change();
So i tried to use .promise() to wait untill ajax call inside change handler will be completed:
$('#first').val('2').change();
$('#wrapper').promise().then( function() {
$('#second').val('b');
console.log('setting value...');
});
But it doesn't work. My question is: how i can wait to end of ajax call, and then set #second value?
Here you have fiddle for this problem: http://jsfiddle.net/W2nVd/
Thanks for your time.