I have a JS function fire when my Dropdown for #Job changes. Three things are suppose to happen.
- First, the
BusinessAreaCodeselects the appropriate item. This is working. - Second, I fetch the Division List to populate the
DivisionCodeDropdown. This works as well. - Lastly, I set the appropriate
DivisionCodejust like I did forBusinessAreaCode. This is not working however.
$('#Job').change(function () {
var selectedValue = this.value;
if (selectedValue != null && selectedValue != '') {
$.getJSON('@Url.Action("GetJobInfo")', { jobId: selectedValue }, function (info) {
console.log(info.BusinessAreaCode);
$('#BusinessAreaCode option[value="' + info.BusinessAreaCode + '"]').attr("selected", "selected");
var ddldivision = $('#DivisionCode');
ddldivision.empty();
ddldivision.append($('<option/>', {
value: "",
text: "-- Select --"
}));
var myValue = $('#BusinessAreaCode').val();
console.log(myValue)
if (myValue != null && myValue != '') {
$.getJSON('@Url.Action("BusinessAreaDivisions")', { businessArea: myValue }, function (divList) {
if (divList.length == 0) {
ddldivision.empty();
ddldivision.append($('<option/>', {
value: "",
text: "N/A"
}));
}
$.each(divList, function (XYZ, data) {
ddldivision.append($('<option/>', {
value: data.Value,
text: data.Text
}));
});
});
}
console.log(`'${info.DivisionCode}'`);
$('#DivisionCode option[value="' + info.DivisionCode + '"]').attr("selected", "selected");
});
}
});
I don’t get an error in console log. I am sure I am returning a proper DivisionCode Value. Could this be a race condition? Any help will be appreciated.
Advertisement
Answer
You’re trying to select the option before populating the list. The order of operations here is:
- Invoke
getJSONto fetch “divisions” - Set the selected “division”
- When
getJSONcompletes, remove all “division” options and re-populate the list
So any selection made, if there were matching options at all, is clobbered as soon as the list is cleared and re-populated.
Move this line:
$('#DivisionCode option[value="' + info.DivisionCode + '"]').attr("selected", "selected");
So that it happens after the list is populated in the asynchronous operation:
$.getJSON('@Url.Action("BusinessAreaDivisions")', { businessArea: myValue }, function (divList) {
// your code, then...
$('#DivisionCode option[value="' + info.DivisionCode + '"]').attr("selected", "selected");
});