嘿我正在尝试创建一个带有下拉菜单的表单,其中包含状态会根据所选国家/地区自动过滤。也就是说,只显示所选国家/地区的状态
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
不能让小提琴工作,但它就是这样的
答案 0 :(得分:0)
使用var声明变量。
var states...
var country...
var options...
如果你不这样做,你就是在创建全局变量
答案 1 :(得分:0)
您需要对代码进行细微更改:
$(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()
}
})
});
您需要在更改功能之外移动状态,因为在else
中执行此操作$states.empty()
,因此下次没有要过滤的html(所有选项和选项组都消失了)。这样就可以将原始值存储在对象中。
我将Afganistan值更改为"ca"
以进行测试(您可以在Afganistan和美国之间切换)