2011-07-25 40 views
1

我一直在试图实现什么应该是一个非常简单的功能,但我没有太多的运气。我在我的ROR应用程序上有一个下拉菜单,它提示用户选择一个国家。从下拉列表中隐藏/显示div的值(使用Javascript和Ruby on Rails)

注:国家名单包含在Constants.rb文件(但基本上是两个可用的选项有:INTERANTIONAL和美国)

我想看到什么发生:当用户选择“美国“的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)隐藏的页面,也不管选用哪国的它仍然隐藏。

回答

0

首先我会改变:onChange to: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'; 
     } 
    } 

更新:

你可以改变你的选择将失踪哈希PARAM:

.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中声明的值。

+0

我正在使用Jquery ......不幸的是改变:onChange to:onchange没有帮助。 –

+0

修订后的答案使用collection_select –

+0

嗯......不幸的是,这似乎没有工作。我肯定有正确的价值(美国),其实这里是我的constants.rb中的代码: COUNTRIES = ['United States','International'] 不幸的是,它仍然没有为一些原因。我非常感谢你的帮助克里斯......谢谢! –

相关问题