Devy
Devy

Reputation: 83

JQuery: Select dropdown which relates to another dropdown

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:

  1. US is selected by using following line

$('#label-country').val('US')

  1. Trigger change function

.trigger('change')

  1. Select "Alaska" state by using

$('#label-country').val('Alaska')

In the end I have:

  1. Country is selected

  2. List of states is changed

  3. State is not selected

Am I missing something in sequence of change function and state selection?

Upvotes: 0

Views: 72

Answers (1)

Janice Zhong
Janice Zhong

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

Related Questions