【发布时间】:2012-09-10 16:58:18
【问题描述】:
我正在尝试解决在 dojo 中加载两个相关下拉列表(国家/州)的古老问题。
我有两个过滤选择来保存国家和州的列表。当用户选择一个国家/地区时,我可以过滤州列表。但是,我无法为当前选定的国家/地区设置州列表中的第一个值。
在下面的示例中,美国和加拿大是唯一的国家/地区。在页面加载时,默认情况下“US”和“Alabama”会正确显示。当我切换到“加拿大”时,我注意到州列表现在包含所有加拿大省份,但我仍然看到“阿拉巴马”仍然被列为州。如何以编程方式设置加拿大省或美国第一个州的第一个值。我正在尝试将过滤选择中的第一项设置为默认值。
感谢阅读。这是我到目前为止所拥有的。
var countries = {
label: "name",
identifier: "countryId",
items: [
{countryId: "USA", name: "United States of America"},
{countryId: "CAN", name: "Canada"},
]
};
var states = {
label: "name",
identifier: "stateId",
items: [
{stateId: "NJ", name: "NewJersey", countryId: "USA"},
{stateId: "IL", name: "Illinois", countryId: "USA"},
{stateId: "CO", name: "Colorado", countryId: "USA"},
{stateId: "OH", name: "Ohio", countryId: "USA"},
{stateId: "AL", name: "Alabama", countryId: "USA"},
{stateId: "ON", name: "Ontario", countryId: "CAN"},
{stateId: "BC", name: "British Columbia", countryId: "CAN"},
{stateId: "QC", name: "Quebec", countryId: "CAN"},
]
};
dojo.addOnLoad(function () {
dojo.connect(dijit.byId('mycountry'), 'onChange', function (country) {
console.log("on change event fired");
loadStates(country);
// set the default state after loading countries, after onChange event.
var firstStateinFilteringSelect = ????
dijit.byId('mystate').attr('displayedValue', firstStateinFilteringSelect);
});
// on page load, load only US states (US is set as a default country)
// the default state is set to "Alabama"
loadStates(dijit.byId('mycountry').attr('value'));
});
function loadStates(country){
console.log(country);
dijit.byId("mystate").query = {countryId: country};
}
</script>
<div dojoType="dojo.data.ItemFileReadStore"
jsId="countryStore"
id="countryStore"
data= "countries"
</div>
<select id="mycountry"
name="country"
dojoType="dijit.form.FilteringSelect"
store="countryStore"
searchAttr="name"
required="true"
value="US"
trim="true">
</select>
<div dojoType="dojo.data.ItemFileReadStore"
jsId="stateStore"
id="stateStore"
data= "states"
</div>
<select id="mystate"
name="state"
dojoType="dijit.form.FilteringSelect"
store="stateStore"
searchAttr="name"
required="true"
value="AL"
trim="true">
</select>
【问题讨论】:
-
_我可以通过在 loadStates(country) 之后调用下面列出的方法来解决问题。但是,对于一个简单的基本任务来说,这似乎过于复杂。 _
function setDefaultState(country) { var filteringSelect = dijit.byId('mystate'); filteringSelect.store.fetch({ query:{ countryId: country }, onComplete : function(items, request) { console.log(items.length); if (items.length > 0) { filteringSelect.setValue(request.store.getValue(items[0], "mystate")); } else { filteringSelect.setValue(""); } } }); }
标签: dojo dijit.form