我一直在尝试实现一个应该非常简单的功能,但我运气不佳。我的 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/