[英]Dynamic country states dropdown menu
嘿,我正在嘗試創建一個帶有下拉菜單的表單,其中包含根據所選國家/地區自動過濾的州。 也就是說,僅顯示所選國家/地區的州
jQuery查詢
$("#shipment_sender_attributes_state_code").parent().hide()
$('#shipment_sender_attributes_country_code').change(function() {
states = $("#shipment_sender_attributes_state_code").html()
country = $('#shipment_sender_attributes_country_code :selected').val()
options = $(states).filter("optgroup[label='" + country + "']").html()
$states = $('#shipment_sender_attributes_state_code')
if (options) {
$states.html(options)
$states.parent().show()
} else {
$states.empty()
$states.parent().hide()
}
})
第一次選擇國家/地區時,此方法有效,但是如果選擇另一個國家/地區,然后返回,則states
變量將保持為空,並且不會顯示任何下拉列表。 有什么建議嗎?
形成:
<optgroup label="us">
<option value="AA">Armed Forces Americas (AA)</option>
<option value="AE">Armed Forces Europe (AE)</option>
<option value="AK">Alaska (AK)</option>
<option value="AL">Alabama (AL)</option>
<option value="AP">Armed Forces Pacific (AP)</option>
<option value="AR">Arkansas (AR)</option>
....
<optgroup label="ca"><option value="AB">Alberta (AB)</option>
<option value="BC">British Columbia (BC)</option>
<option value="MB">Manitoba (MB)</option>
<option value="NB">New Brunswick (NB)</option>
<option value="NL">Newfoundland and Labrador (NL)</option>
....
編輯JSfiddle
不能完全使小提琴起作用,但這是這樣的
使用var聲明變量。
var states...
var country...
var options...
如果不這樣做,那么您正在創建全局變量
您需要對代碼進行一些小的更改:
$(function(){
$("#shipment_sender_attributes_state_code").parent().hide()
var states = $("#shipment_sender_attributes_state_code").html()
$('#shipment_sender_attributes_country_code').change(function() {
var country = $('#shipment_sender_attributes_country_code :selected').val()
var options = $(states).filter("optgroup[label='" + country + "']").html()
var $states = $('#shipment_sender_attributes_state_code')
if (options) {
$states.html(options)
$states.parent().show()
}
else {
$states.empty()
$states.parent().hide()
}
})
});
您需要將狀態移動到change函數之外,因為在else
函數中,您需要執行$states.empty()
,因此下次沒有html可以過濾(所有選項和optgroups都消失了)。 這樣,您可以將原始值存儲在對象中。
我出於測試目的將Afganistan值更改為"ca"
(您可以在Afganistan和美國之間切換)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.