javascript - 下拉菜单中的值隐藏/显示 div(使用 Javascript 和 Ruby on Rails)

标签 javascript jquery ruby-on-rails drop-down-menu haml

我一直在尝试实现一个应该非常简单的功能,但我运气不佳。我的 ROR 应用程序上有一个下拉菜单,提示用户选择一个国家/地区。

注意:国家列表包含在 Constants.rb 文件中(但基本上两个可用选项是:Interantional 和 United States。)

我希望看到发生的情况:当用户选择“美国”时,div id state_nav(包含带有州列表的下拉菜单的div)将显示...如果用户选择国际, state_nav 菜单将保持隐藏状态。

这是迄今为止我所拥有的代码(我正在使用 HAML)

JavaScript 位于 html 的 header

:javascript
  function showDiv(obj)
  {
      if(obj[obj.selectedIndex].value == 'United States')
      {
          document.getElementById('state_div').style.display = 'block';
      }
      else
      {
          document.getElementById('state_div').style.display = 'none';
      }
  }

这是位于 html.HAML 正文中的代码

  .section
    %div{:class => "label_leftalign field"}
        %p.information
          please list the country, state (if applicable), and city where you're located
        = f.label :country, "Location"
        = f.select :country, COUNTRIES, :onChange => "showDiv(this)", :prompt => true

    %div{:class => "label_leftalign field"}
      #state_div{:style => "display:none;"}
          = f.label :state, " ".html_safe
          = f.select :state, STATES, :prompt => true

目前...当我加载页面时,“州”下拉菜单 (#state_div) 被隐藏,并且无论选择哪个国家/地区,它都保持隐藏状态。

最佳答案

首先我会将 :onChange 更改为 :onchange。然后向你的 js 中抛出一个警报,看看 JS 是否至少被调用:

:javascript
  function showDiv(obj)
  {
      alert(obj[obj.selectedIndex].value);
      if(obj[obj.selectedIndex].value == 'United States')
      {
          document.getElementById('state_div').style.display = 'block';
      }
      else
      {
          document.getElementById('state_div').style.display = 'none';
      }
  }

更新:

您可以更改您的选择以包含缺少的哈希参数:

.section
  %div{:class => "label_leftalign field"}
      %p.information
        please list the country, state (if applicable), and city where you're located
      = f.label :country, "Location"
      = f.select :country, COUNTRIES, {}, :onChange => "showDiv(this)", :prompt => true
  %div{:class => "label_leftalign field"}
    #state_div{:style => "display:none;"}
        = f.label :state, " ".html_safe
        = f.select :state, STATES, :prompt => true

我在本地尝试过,效果很好。确保选项字段的值反射(reflect)您在 obj[obj.selectedIndex].value 中断言的值。

关于javascript - 下拉菜单中的值隐藏/显示 div(使用 Javascript 和 Ruby on Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6819483/

相关文章:

css - stylesheet_link_tag 或 @import

javascript - 将 SQL 日期时间转换为以本地输入类型日期时间显示

php - yii2:jquery 如果 gridview 列包含特定值则更改颜色

javascript - 使用后退和前进按钮快速导航时如何防止加载多个 View

javascript - 我如何将参数传递给backbone.js中的通用事件处理程序

css - Rails Font-Awesome 不显示 - 使用错误的文件名

ruby-on-rails - 回形针、大文件上传和 AWS

javascript - 你能安排事件回调的冒泡顺序吗?

javascript - Clojure 到 JavaScript

javascript - 收到错误 : TypeError: $(. ..).live 不是函数