I am using Eric Hynd’s wonderful multiselect plug in to populate a couple of drop downs.
One is the business units:
…
$('#lbBusinessUnits').multiselect({
height: "auto",
selectedList: 20
});
…
The second is the business areas (#lbBusinessAreas).
…
$('#lbBusinessAreas').multiselect({
selectedList: 20
});
…
The list of areas is updated when a unit is checked like this:
// Business Units List Box Change
$('#lbBusinessUnits').bind("multiselectclick", function (event, ui) {
var selectedPeriod = $('#ddlSalesPeriods').val();
var selectedUnit = ui.value;
var selectedUnitText = ui.text;
var checkedUnit = ui.checked;
var areChecked = $(this).multiselect("getChecked").map(function () { return this.value; }).get();
if (areChecked.length > 0) {
url = '/InvoiceException/LoadBusinessareasBySalesPeriodBusinessUnit';
$.getJSON(url, { selectedSalesPeriod: selectedPeriod, selectedBusinessUnits: areChecked }, function (areas) {
var areaSelect = $('#lbBusinessAreas');
areaSelect.empty();
$.each(areas, function (index, optionData) {
areaSelect.append($('<option/>', { value: optionData.Id, text: optionData.Name }));
});
});
}
else {
var url = '/InvoiceException/LoadBusinessAreasBySalesPeriod';
$.getJSON(url, { selectedSalesPeriod: selectedPeriod }, function (areas) {
var areaSelect = $('#lbBusinessAreas');
areaSelect.empty();
$.each(areas, function (index, optionData) {
areaSelect.append($('<option/>', { value: optionData.Id, text: optionData.Name }));
});
});
}
$('#lbBusinessAreas').multiselect("refresh");
});
The JSON results are handled by an MVC3 controller and are coming back correctly from the URL calls. I.E. the data returned looks right.
However the area box (#lbBusinessAreas) does not get updated properly after a click. It seems to be one click behind. It appears that there is a race condition occuring with the refresh of the box.
When I put it in Firebug and put a breakpoint at the point it calls multiselect(“refresh”) everything works properly when I step through the debugger and acts exactly like it should.
Is this truly a race condition where the refresh is finishing before the options get updated? Is it because it’s an ajax/getJson call?
Do I need to move the call to refresh out or figure out someway to ensure order of operation? I.E. the options need to finish updating and then the refresh needs to occur.
I thought a simple refresh after it was all said and done would work. A /headbonk moment as you realize that you have to wait for the success of the getJson calls to come back. So I had to move the refresh into the success function of each call. Posted change/answer here in case anyone else is having a “oh duh” moment.