views:

25

answers:

1

I have a drop-down box that populates itself based on the value of another drop-down, using jQuery's ajaxy goodness. I do this with the $(document).ready function, with this being the relevant code...

$(document).ready(function() {
  populateFirstDropDownBox();

  $("#firstBox").change(function() {
    populateSecondDropDownBox($("#firstBox option:selected").val());
  }); 

  // Do this on initial page load to populate second box
  populateSecondDropDownBox($("#firstBox option:selected").val());
});

This works great in Firefox and IE, but not in Chrome. Chrome seems to not immediately populate the first drop down box so $("#firstBox option:selected").val() ends up not resolving.

What is the best way of ensuring Chrome has populated the dropdown?

Edit: added more

function populateFirstDropDownBox() {
  $.post("ajax/getFirstBox", function(json) {
    var options = makeOptionList(json);
$("#firstBox").html(options);
$("#firstBox").triggerHandler("change");
  })
}

function populateSecondDropDownBox(firstBox) {

  $.post("ajax/getSecondBox", {firstBox: firstBox}, function(json) {
    var options = makeOptionList(json);
$("#secondBox").html(locationOptions);
$("#secondBox").triggerHandler("change");
  })
}

function makeOptionList(json) {
  data = eval(json);
  var options = "";

  for (var optIndex = 0; optIndex < data.length; ++optIndex) {
    options += "<option value='" + data[optIndex].value + "'>" + data[optIndex].key + "</option>"
  }

  return options;
}
A: 

Remove this:

// Do this on initial page load to populate second box
populateSecondDropDownBox($("#firstBox option:selected").val());

Since this code:

$("#firstBox").triggerHandler("change")     

Will trigger it once the first dropdown is loaded.

Better yet, populate your dropdowns in the HTML on the server and save two round trips. Your users will appreciate it.

noah
True, but I still have my initial problem, ("#firstBox option:selected") does not populate immediately in Chrome. Works like a charm in IE and Firefox. However, in Chrome, since that value is not yet set, populateSecondDropDownBox fails. I guess I'm just looking for a way to force Chrome to populate the firstBox element.
majorpayne27
You're making an async request to load the data. Firefox and IE may load it fast enough that it seems immediate, but it's not. When your users try to load the page they will have a longer latency between them and the server and will encounter the same problem in any browser. The way you have structured your code, you have to do all the handling of the 2nd box in the Ajax response handler for it to work consistently.
noah