【问题标题】:select drop down choose country depending on the location of state in the array选择下拉选择国家,具体取决于数组中州的位置
【发布时间】:2014-01-31 03:18:35
【问题描述】:

我的国家/地区是一个哈希数组,如下所示

countries = [
      {
        "country" => {
          "name" => "USA"
          "id" => "123"
        },
        "states" => [
          {
            "name" => "Alaska",
            "id"=> "b2"
          },
          {
            "name"=> "Kansas",
            "id"=> "b6"
          }
        ]
      },
      {
        "country" => {
          "name" => "India"
          "id" => "123"
        },       
        "states" => [
          {
            "name"=> "Karnataka",
            "id"=> "b31",
          },
          {
            "name" =>"Punjab",
            "id"=> "b21"
          }
        ]
      }
    ]

在我的 ruby​​ 代码中,我得到了上面列出的所有州和国家的数组:

def country
   countries.map { |country|
   [country.name, country.id]
 }
end

def state
  countries.flat_map { |country|
  country.states.map { |state|
    [state.name, state.id]
  }
}
end

My form select_tag is as follows:

= select_tag 'state', options_for_select(state)
= select_tag 'country', options_for_select(country)

上面的选择下拉菜单会拉出所有州和国家。

现在,我需要调整下拉选择,以便如果任何州属于数组的第一个条目,则从同一条目中选择国家,依此类推。

在上面的示例中,如果选择堪萨斯州,请选择美国作为国家/地区。

如果选择旁遮普,则选择印度作为国家。

我不知道它是否可能。这对我来说似乎太hacky了。

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您可以做的是创建一个以 state id 为 key 和 country id 为 value 的哈希

    喜欢这个

    COUNTRY.inject({}) do |hash, ele| 
         ele['states'].each {|state| hash[state['id']] = ele['country']['id']} 
      hash
    end
    

    你会得到这样的哈希

    {"b2"=>"123", "b6"=>"123", "b31"=>"123", "b21"=>"123"} 
    

    在您的视图中将此哈希加载为 json 并在状态选择更改时编写 jquery 事件。 在州上,从 json 对象中找到国家/地区 id,然后选择该 id 作为该州的国家/地区。

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 2014-10-27
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 2018-03-27
      相关资源
      最近更新 更多