开发者

jQuery SelectedItem Population

开发者 https://www.devze.com 2022-12-21 12:24 出处:网络
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..

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")开发者_C百科.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;
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号