首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用Jquery设置受约束的select?

如何使用Jquery设置受约束的select?
EN

Stack Overflow用户
提问于 2013-01-04 02:12:30
回答 1查看 98关注 0票数 1

根据用户选择的国家,我想实现对县的自动约束选择。

当用户在乡村字段中选择美国时,应该只在专区选择字段中显示像加利福尼亚、纽约或etcs这样的美国州。

国家模型

  • id
  • 名字

模型

  • id
  • country_id

现在我像这样展示这些领域

代码语言:javascript
代码运行次数:0
运行
复制
<% resource.build_user_profile if resource.user_profile.nil? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put, :class => 'form-horizontal' }) do |f| %>
  <%= devise_error_messages! %>

<%= f.fields_for :user_profile do |profile_form| %>

 <label class="control-label"><%= profile_form.label :country_id %></label>
 <%= profile_form_select :country, options_for_select(Countryy.all.map{ |g| [g.name, g.id] }) %>

 <label class="control-label"><%= profile_form.label :prefecture_id %></label>
 <%= profile_form_select :prefecture, options_for_select(Prefecture.all.map{ |g| [g.name, g.id] }) %>

<% end %>
EN

回答 1

Stack Overflow用户

发布于 2013-01-04 02:28:59

如果您修改HTML以编写自定义的select选项生成器,您可以使用如下所示的JS。

JavaScript:

代码语言:javascript
代码运行次数:0
运行
复制
$(".country_select").change(function() {
  var country_id = $(this).val();
  if(country_id) {
    $(".prefecture_select option[country_id="+country_id+"]").hide();
  } else {
    $(".prefecture_select option").show();
  }
}

如果您不想编写自定义的select助手,那么最简单的方法就是创建多个选择,并使用JS只显示与所选国家匹配的选项。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14150171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档