Rails 4:基于选择字段值的coffeescript条件显示

蒂博·克莱门特(Thibaud Clement)

在我的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_formatdiv的值发生变化时我也应该对其进行初始化,但是我不确定如何使它工作。

任何的想法?

吉尼尔

该代码的问题在于,它没有观察到select字段值的变化。您可以通过将整个代码放在change事件绑定回调中来实现此目的。我还建议进行少量重构,以使您的代码看起来更整洁。

$(document).ready ->
  $('#post_format')
    .on 'change', ->
      grades = { 'A': 'GREAT', 'B': 'GOOD', 'C': 'OK', 'D': 'BAD' }
      $('#post_format_analysis').html grades[@value]

    .trigger('change')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章