Context in jQuery ajax function
I have this jQuery function for chained drop down boxes:
function updateCargoDestinations() {
$.ajax({
url: "/truckingmanagement/account/getAccountUserCargoDestinations",
data: "id=" + this.value,
cache: false,
success: function(html) {
$("#cargoDestination").html(html);
}
});
}
$(document).ready(function() {$("#account").change(updateCargoDestinations);});
It works great, but I also need the function to run one time when the page loads so the chained drop down box will populate correctly. I have tried to set the context in the function like this:
context: ("#account")
but that is not working. How can I make it so this function runs one time when the 开发者_JS百科page loads AND runs when the observed drop down box is changed?
Set this.value
in a variable then check for undefined
. If undefined
set to whatever value it needs to initially populate the dropdown.
function updateCargoDestinations() {
var selectId = this.value;
if (typeof selectId === "undefined") {
selectId = "whatever_you_need_here";
}
$.ajax({
url: "/truckingmanagement/account/getAccountUserCargoDestinations",
data: "id=" + selectId,
cache: false,
success: function(html) {
$("#cargoDestination").html(html);
}
});
}
$(document).ready(function() {
updateCargoDestinations();
$("#account").change(updateCargoDestinations);
});
Fiddle for undefined check: http://jsfiddle.net/kfJvA/1/
精彩评论