[英]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.