Reputation: 83
UPDATED I have 2 dropdowns (input select) - one for countries (#label-country), another - for states (#label-state). Once user selects country - list of states changes. Following code changes list of states, once country is selected:
$('#label-country').change(function() {
var countryinput = $('#label-country').val();
$.post('func/region.php', {countryinput:countryinput}, function(states) {
$('#label-state option').remove();
$('#label-state').append(states);
});
});
It works fine, if user manually selects country and then state for that country. But in some occasions I want to be able to preselect country and state.
I found out that following code doesn't work - country is selected as needed, but state - not:
$('#label-country').val('US').trigger('change');
$('#label-state').val('Alaska');
Flow which I have in mind:
$('#label-country').val('US')
.trigger('change')
$('#label-country').val('Alaska')
In the end I have:
Country is selected
List of states is changed
State is not selected
Am I missing something in sequence of change function and state selection?
Upvotes: 0
Views: 72
Reputation: 878
$('#label-country').val('US').trigger('change');
is triggering a event where has an asynchronous ajax post function, which is the exact cause of your issue.
Not until the ajax .done()
function triggered, your next line $('#label-state').val('Alaska');
has already been called, by the time it happens, your $('#label-state')
hasn't got a value yet, to prove this, you can use a for loop to log its values.
So all you need to do, in this case, is to put something like
if(countryInput=="US") $('#label-state').val('Alaska');
inside of $.post
function, and remove $('#label-country').val('US').trigger('change');
.
Upvotes: 0