我需要在加载后从下拉列表中选择一个值:
编辑:在与我有关的视图相关的脚本中:
//Dropdown cascade call when trigger is called and fill councilDropdown:
$("#districtDropdown").cascade({
url: "/Address/ListCouncilByDistrict",
paramName: "districtId",
firstOption: 'Selecione o Concelho...',
childSelect: $("#councilDropdown")
});
$("#PostalCode").keyup(function () {
loadPTPostalCode();
});
$("#PostalCodeExtension").keyup(function () {
loadPTPostalCode();
});
function loadPTPostalCode()
{
if ($("#PostalCode").val() >= 1000) {
$.ajax({
url: '/Address/GetPTPostalCode',
type: "POST",
dataType: "json",
data: { postalCode: $("#PostalCode").val(), postalCodeExtension: $("#PostalCodeExtension").val() },
success: function (data) {
if (data != null) {
$("#districtDropdown").val(data.PTDistrict_Id); // Set the Dropdown value
$('#districtDropdown').trigger('change'); // Trigger (force the dropdown to load
// *** This is done to soon, the dropdownlist of the Councils is not all loaded yet ***
$("#councilDropdown").val(data.PTCouncil_Id);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus)
}
});
}
}
编辑:视图
@model Heelp.ViewModels.AddressPTViewModel
<h2>Create</h2>
@using (Ajax.BeginForm(MVC.Address.CreateAddressPT(), new AjaxOptions { OnSuccess = "showLoginConfirmationResultMessage" }, new { @id = "AddressForm" }))
{
@Html.AntiForgeryToken()
<div class="address1">
@Html.LabelFor(model => model.Address1)
@Html.TextBoxFor(model => model.Address1)
@Html.ValidationMessageFor(model => model.Address1)
</div>
<div class="address2">
@Html.TextBoxFor(model => model.Address2)
@Html.ValidationMessageFor(model => model.Address2)
</div>
<div class="city">
@Html.LabelFor(model => model.City)
@Html.TextBoxFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="postalCode">
@Html.DisplayNameFor(m => m.PostalCode)
@Html.TextBoxFor(m => m.PostalCode, new { @Value = "" })
@Html.ValidationMessageFor(m => m.PostalCode)
</div>
<div class="postalCodeExtension">
@Html.LabelFor(model => model.PostalCodeExtension)
@Html.TextBoxFor(model => model.PostalCodeExtension)
@Html.ValidationMessageFor(m => m.PostalCodeExtension)
</div>
<div class="postalCodeCity">
@Html.LabelFor(model => model.PostalCodeCity)
@Html.TextBoxFor(model => model.PostalCodeCity)
@Html.ValidationMessageFor(m => m.PostalCodeCity)
</div>
<div id="district">
@Html.DisplayNameFor(m => m.PTDistrict_Id)
@Html.DropDownListFor(m => m.PTDistrict_Id, Model.PTDistrictList, HeelpResources.PTDistrictViewDropDownListFirstRecord, new { id = "districtDropdown" })
@Html.ValidationMessageFor(m => m.PTDistrict_Id)
</div>
<div id="council">
@Html.DisplayNameFor(m => m.PTCouncil_Id)
@Html.DropDownListFor(m => m.PTCouncil_Id, Model.PTCouncilList, HeelpResources.PTCouncilViewDropDownListFirstRecord, new { id = "councilDropdown" })
@Html.ValidationMessageFor(m => m.PTCouncil_Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
编辑:
级联功能:
// Cascade function
(function ($) {
$.fn.cascade = function (options) {
var defaults = {};
var opts = $.extend(defaults, options);
return this.each(function () {
$(this).change(function () {
var selectedValue = $(this).val();
if (selectedValue == '') {
opts.childSelect.empty();
return;
}
var params = {};
params[opts.paramName] = selectedValue;
$.post(opts.url, params, function (items) {
//$.getJSON(opts.url, params, function (items) {
opts.childSelect.empty();
if (opts.firstOption != "")
opts.childSelect.append(
$('<option/>')
.attr('value', '')
.text(opts.firstOption));
$.each(items, function (index, item) {
// alert(opts.firstOption);
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
});
});
});
};
})(jQuery);
但是当我这样做时,由于Dropdownlist仍然没有加载,val()还没有。
例如,如果我之前发出警告消息,它可以正常工作,因为它是加载下拉列表的时间。
如何在加载下拉列表后设置理事会下拉列表的值?
答案 0 :(得分:4)
根据您的要求“仅在下拉列表加载后设置理事会下拉列表的值”。
您需要执行同步Ajax请求。您可以将 async 选项指定为 false 以获取同步Ajax请求。
$.ajax({
url: '/Address/GetPTPostalCode',
type: "POST",
dataType: "json",
data: { postalCode: $("#PostalCode").val(), postalCodeExtension: $("#PostalCodeExtension").val() },
success: function (data) {
if (data != null) {
$("#districtDropdown").val(data.PTDistrict_Id);
$('#districtDropdown').trigger('change');
// *** This is done to soon, the dropdownlist of the Councils is not all loaded yet ***
$("#councilDropdown").val(data.PTCouncil_Id);
}
},
async: false
});
答案 1 :(得分:3)
我会更新级联插件,以便在更新ddl时触发事件。
(function ($) {
$.fn.cascade = function (options) {
var defaults = {};
var opts = $.extend(defaults, options);
return this.each(function () {
$(this).change(function () {
// #### store reference to changed element for later ####
var self = this,
selectedValue = $(this).val();
if (selectedValue == '') {
opts.childSelect.empty();
return;
}
var params = {};
params[opts.paramName] = selectedValue;
$.post(opts.url, params, function (items) {
//$.getJSON(opts.url, params, function (items) {
opts.childSelect.empty();
if (opts.firstOption != "")
opts.childSelect.append(
$('<option/>')
.attr('value', '')
.text(opts.firstOption));
$.each(items, function (index, item) {
// alert(opts.firstOption);
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
// #### Trigger event ####
self.trigger("update");
});
});
});
};
})(jQuery);
现在你可以绑定到:
...
// *** #### fixed #### This is done to soon, the dropdownlist of the Councils is not all loaded yet ***
$("#councilDropdown").on("updated",function(){
$(this).val(data.PTCouncil_Id);
});
}
答案 2 :(得分:1)
尝试在下拉列表中创建两个事件1.自定义事件和2.更改事件
当用户手动更改然后下拉值时,将触发更改事件。
$('#dictrctDropdown').change(function (event){
$('#dictrctDropdown').trigger('custom');
});
$('#dictrctDropdown').on('custom', function (event, param1){
// Load council dropdown
if(param1){
$("#councilDropdown").val(param1);
}
});
来自“/ Address / GetPTPostalCode”成功回调为“dictrctDropdown”提出自定义事件
function loadPTPostalCode()
{
if ($("#PostalCode").val() >= 1000) {
$.ajax({
url: '/Address/GetPTPostalCode',
type: "POST",
dataType: "json",
data: { postalCode: $("#PostalCode").val(), postalCodeExtension: $("#PostalCodeExtension").val() },
success: function (data) {
if (data != null) {
$.getJSON('disctrictURL','data to post (if any)',function(response){
//Load district dropdown
/*
$.each(items, function (index, item) {
// alert(opts.firstOption);
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
*/
$("#districtDropdown").val(data.PTDistrict_Id); // Set the Dropdown value
});
//Now use district id load council dropdown and set value
$.getJSON('councilURL','data to post (if any)',function(response){
//Council dropdown
$("#districtDropdown").val('council id'); // Set the Dropdown value
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus)
}
});
}
希望这会有所帮助!
答案 3 :(得分:1)
我想说这里有两种方法。
最佳做法是为您的级联添加回调功能。可以这样做:
...
$.post(opts.url, params, function (items) {
//$.getJSON(opts.url, params, function (items) {
opts.childSelect.empty();
if (opts.firstOption != ""){
opts.childSelect.append(
$('<option/>')
.attr('value', '')
.text(opts.firstOption));
$.each(items, function (index, item) {
// alert(opts.firstOption);
opts.childSelect.append(
$('<option/>')
.attr('value', item.Id)
.text(item.Name)
);
});
if( typeof(opts.callback) == "function" )opts.callback();//issue callback
}
});
...
这将通过设置级联来使用:
$("#districtDropdown").cascade({
url: "/Address/ListCouncilByDistrict",
paramName: "districtId",
firstOption: 'Selecione o Concelho...',
childSelect: $("#councilDropdown"),
callback: function(){ districtCallback(); }
});
并以您想要的任何方式定义:
function districtCallback(){
$("#councilDropdown").val($("#districtDropdown").val());
}
又快又脏.. jsFiddle demo
success: function (data) {
if (data != null) {
$("#districtDropdown").val(data.PTDistrict_Id); // Set the Dropdown value
$('#districtDropdown').trigger('change'); // Trigger (force the dropdown to load
(function councilVal(){
if( typeof($("#councilDropdown").val()) != "undefined" ){
$("#councilDropdown").val(data.PTCouncil_Id);
}else{
setTimeout(councilVal,50);
}
})()
}
}