我有使用兩個下拉列表的形式。一旦第一個下拉選擇值發生變化,應用程序就會進行Ajax調用,以便在第二個下拉列表中顯示新列表。
將其視爲在選定國家/地區過濾的州/省份列表。
第一個下拉菜單是countryDropDown,第二個下拉菜單是statesDropDown。
代碼示例
JSP
<html:select name="countries"
property="countryName"
indexed="true"
onchange="onCountryChange(this, 'states${index}')">
<html:optionsCollection name="myViewModel" property="countries" />
</html:select>
<html:select styleId="states${index}"
name="states"
property="name"
indexed="true">
<html:optionsCollection name="myViewModel" property="states" />
</html:select>
的Javascript
function onCountryChange(countriesDropDown, statesDropDownId) {
var country = $(countriesDropDown).val();
$.ajax({
type: 'POST',
url: makeURL('/ent/refreshStates.do'),
async: false,
data: "country:" + country,
success: function(states) {
populate(statesDropDownId, states);
},
failure: function(e) {
showAlert(e);
}
});
}
// In the following function, states is a list of ListValueBean.
function populate(statesDropDownId, states) {
var statesDropDown = $(statesDropDownId);
statesDropDown.empty();
for(var i=0; i<states.length; i++) {
statesDropDown.append("<option></option>")
.attr("value", states[i].value)
.text(states[i].label);
}
}
渲染HTML
<select name="states[0].state" id="states0" data-size="10" style="display: none;">
<option value="5052">MO</option>
<option value="5051" selected="selected">CA</option>
...
</select>
<div class="btn-group boostrap-select">
<button type="button" class="btn dropdown-toggle selectpicker btn-default" data-toggle="dropdown" data-id="states0" title="5051">
<span class="filter-option pull-left">CA</span>
" "
<span class="caret">::before</span>
</button>
<div class="dropdown-menu open">
<ul class="dropdown-menu inner selectpicker" role="menu">
<li rel="0" class="selected">
<a tabindex="0" class style>
<span class="text">CA</span>
<i class="glyphicon glyphicon-ok icon-ok check-mark"></i>
</a>
</li>
</ul>
</div>
</div>
這似乎是select
呈現而是通過引導隱藏,我看到了控制變爲一個按鈕。
所以,即使選擇得到填充,我不能得到這個包裝的按鈕更新基於它隱藏的選擇內容。 :(
現狀
目前的行爲是往返於服務器工作得很好,一切都只是預期,除了它永遠不會在下拉更新狀態下來。
那麼如何使工作?
好吧,從快速瀏覽我不確定你的ID查找狀態下降將在它的前面有'#',使它成爲一個有效的ID選擇器。你要麼將它放在onchange調用的字符串中,要麼將其附加到填充方法的前面。 – Taplar
你可以在jsfiddle中創建一個例子,以便我們可以玩你的代碼? – rm4
如果你做'console.log(statesDropDown)'它是否返回你期望的對象? – kyle