I have two select controls on my web page (Bootstrap Select2):
<div class="form-group">
<label>Client: </label>
<select id="ddlClient" class="form-control select2 subselect">
<option value="0">Select client</option>
</select>
</div>
<div class="form-group">
<label>Policy: </label>
<select id="ddlPolicy" class="form-control select2">
<option value="0">...</option>
</select>
</div>
I have a listener on the first one ddlClient
to fill values of the second one based on client selection:
$(document).ready(function () {
$('.content').on('change', 'select.subselect', function () {
var subItems = "<option value='0'>... select policy ... </option>";
var idSelect = $('#ddlClient').val();
// fill list
$.getJSON("@Url.Action("GetPolicies", "Home")", {id: idSelect }, function (data) {
$.each(data, function (index, item) {
subItems += "<option value='" + item.value + "'>" + item.text + "</option>";
});
$("#ddlPolicy").html(subItems);
$("#ddlPolicy").val('0');
});
});
Now, in some cases I have to programatically change both dropdowns and the problem is, that the function below (line 3 and 4) obviously do not wait for the change
event to finish. So, policy is not selected corectly:
$('#ddlClient').val(someClientValue);
$('#ddlClient').trigger('change'); //trigger change so that SELECT2 changes text
$('#ddlPolicy').val(somePolicyValue);
$('#ddlPolicy').trigger('change'); //trigger change so that SELECT2 changes text
How do I wait for change
to finish on ddlClient
before calling $('#ddlPolicy').val(somePolicyValue);
?
What I've tried and doesn't work (How to get jQuery to wait until an effect is finished?):
$('#ddlClient').val(someClientValue);
$('#ddlClient').change().promise().done(function () {
$('#ddlPolicy').val(somePolicyValue);
$('#ddlPolicy').trigger('change');
}
I have also tried implementing .when
:
$('#ddlClient').val(someClientValue);
$.when($('#ddlClient').trigger('change')).then(function () {
$('#ddlPolicy').val(somePolicyValue);
$('#ddlPolicy').trigger('change');
}
but the problem remains.