动态国家/地区状态下拉菜单

Dynamic country states dropdown menu

本文关键字:状态 下拉菜单 地区 国家 动态      更新时间:2023-09-26

嘿,我正在尝试创建一个带有下拉菜单的表单,其中包含根据所选国家自动筛选的状态。也就是说,只显示所选国家的状态

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

不能完全让小提琴工作,但它有点像这个

http://jsfiddle.net/d6cm5v6g/2/

使用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()
    }
  })
});  

您需要将状态移动到更改函数之外,因为在else中,您执行的是$states.empty(),所以下次没有html可供筛选(所有选项和optgroup都不存在)。通过这种方式,可以将原始值存储在对象中。

出于测试目的,我将阿富汗值更改为"ca"(您可以在阿富汗和美国之间切换)

工作小提琴:http://jsfiddle.net/robertrozas/4vxjpjLv/2/