【问题标题】:Value from dropdown hides/shows div (using Javascript and Ruby on Rails)下拉列表中的值隐藏/显示 div(使用 Javascript 和 Ruby on Rails)
【发布时间】:2011-07-25 16:41:27
【问题描述】:

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

注意:国家/地区列表包含在 Constants.rb 文件中(但基本上两个可用选项是:国际和美国。)

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

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

javascript位于html的头部

: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) 处于隐藏状态,无论选择哪个国家/地区,它都保持隐藏状态。

【问题讨论】:

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


    【解决方案1】:

    首先我会将 :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
    

    我在本地尝试过,效果很好。确保您的选项字段的值反映了您在 obj[obj.selectedIndex].value 中声明的值。

    【讨论】:

    • 我正在使用 Jquery... 不幸的是,将 :onChange 更改为 :onchange 没有帮助。
    • 使用 collection_select 的修订答案
    • 嗯...不幸的是,这似乎不起作用。我肯定有正确的值(美国),事实上,这是我的 constants.rb 中的代码: COUNTRIES = ['United States', 'International'] 不幸的是,由于某种原因它仍然无法正常工作。非常感谢您的帮助,克里斯...谢谢!
    • 当您在 js 中添加该警报行时,是否会弹出正确的值? alert(obj[obj.selectedIndex].value);
    • 克里斯,那个值会在哪里弹出?
    猜你喜欢
    • 2012-01-18
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多