【发布时间】:2016-03-06 03:30:18
【问题描述】:
在我的 Rails 4 应用程序中,我有以下表单(与我的 Post 模型相关):
<div class="field">
<%= f.label :format, "FORMAT" %>
<%= f.select :format, ['A', 'B', 'C', 'D'] %>
</div>
呈现以下 html 代码:
<div class="field">
<label for="post_format">FORMAT</label>
<select name="post[format]" id="post_format">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</div>
现在,我需要在页面上显示特定消息,在 <div id="post_format_analysis"></div> 内并实时(无需重新加载页面),具体取决于用户选择的选项。
所以,我在我的 posts.coffee 文件中尝试了这个:
$(document).ready ->
post_format = document.getElementById("post_format")
if post_format.options[post_format.selectedIndex].value == 'A'
$('#post_format_analysis').html 'GREAT'
else if post_format.options[post_format.selectedIndex].value == 'B'
$('#post_format_analysis').html 'GOOD'
else if post_format.options[post_format.selectedIndex].value == 'C'
$('#post_format_analysis').html 'OK'
else if post_format.options[post_format.selectedIndex].value == 'D'
$('#post_format_analysis').html 'BAD'
问题是,这仅在页面第一次加载时有效,即:与默认选择的值(A)对应的消息(GREAT)是显示出来。
但是,当用户选择另一个值时,消息不会更新。
我认为问题在于我用$(document).ready -> 初始化代码,而当#post_format div 的值发生变化时我也应该初始化它,但我不知道如何使它工作。
有什么想法吗?
【问题讨论】:
-
将 if else 包装在更改事件绑定中。
$('#post_format').on 'change', -> -
谢谢,这行得通。有没有办法在页面加载时也考虑选择的值,所以即使用户第一次加载页面时也会显示正确的消息,而不仅仅是在他选择不同的值时?可能是
$('#post_format').on 'load, change', ->之类的? -
或者
preventDefault可能? -
绑定后直接调用
$('#post_format').change()。 -
酷,谢谢。随时提供此解决方案作为答案,我很乐意接受。
标签: ruby-on-rails ruby-on-rails-4 drop-down-menu coffeescript conditional