【问题标题】:Rails 4 & Coffee Script form helper to hide on unchecked fieldRails 4 和 Coffee Script 表单助手隐藏在未选中的字段上
【发布时间】:2015-09-06 18:03:46
【问题描述】:

我正在尝试在 Rails 4 中制作应用程序。

我对表单使用简单的表单,并有一个 js 表单帮助文件,我使用它来隐藏或显示表单元素,具体取决于用户在表单中移动时如何回答问题。

我的问题是这个js函数在初始创建时工作正常,但是如果我回来编辑表单,当draft属性== false时会显示提醒id内容。

还有其他方法可以解决这个问题吗?

我的表格有:

  <%= f.simple_fields_for :scope do |finalises_s| %>
      <%= finalises_s.simple_fields_for :finalise do |dr| %>

          <div class="row">
            <div class="col-md-3 col-md-offset-1">

              <%= dr.label :draft, 'Would you like to save this draft and finish it later?', class: 'question-project' %>
            </div>
            <div class="col-md-7">
              <%= dr.collection_radio_buttons :draft, [[true, ' Yes, save a draft'], [false, ' No, publish it']], :first, :last, {:item_wrapper_class => 'fixradio'}, {:class => "response-project"} %>
            </div>
          </div>
          <div id="reminder">
            <div class="row">
              <div class="col-md-3 col-md-offset-1">

                <%= dr.label :reminder, 'Would you like a reminder to complete this draft?', class: 'question-project' %>
              </div>
              <div class="col-md-7">
                <%= dr.collection_radio_buttons :reminder, [[true, ' Yes'], [false, ' No']], :first, :last, {:item_wrapper_class => 'fixradio'}, {:class => "response-project"} %>
              </div>
            </div>

我的 js form-helper 文件有:

if $("input:radio[name='"+ inString + "[scope_attributes][finalise_attributes][draft]']").is(':checked')
  $('#reminder').show()
else
  $('#reminder').hide()
$(document).on 'change', "input:radio[name='"+ inString + "[scope_attributes][finalise_attributes][draft]']", ()->
  if $(this).val() == 'true'
    $('#reminder').show()
  else
    $('#reminder').hide()

【问题讨论】:

    标签: ruby-on-rails forms coffeescript


    【解决方案1】:

    可能有几种不同的方法可以做到这一点,但我做了非常相似的事情。

    将 id 或类附加到单选按钮上,以便以后绑定(在我的例子中,对于每个单选/值组合,我添加了一个独特的类,例如 class: this_radio_value_true)。

    同样,将 id 或 class 附加到您想要影响的标记部分(在我的情况下,我将 id 添加到要隐藏/显示的 form_group 中,例如 id: stuff_to_control)。

    为这些元素触发 jQuery:

    $('.this_radio_value_true').on('click', function() {
      $('#stuff_to_control').show();
    });
    
    $('.this_radio_value_false').on('click', function() {
      $('#stuff_to_control').hide();
    });
    

    【讨论】:

      【解决方案2】:

      这可能是因为 TurboLinks。你不能使用$(document).on 'change'。您必须列出 TurboLink 事件。 Rails 不会每次都加载整个页面。它只加载布局内的内容。你必须使用

       $(document).on 'ready page:load', ->
      

      这是文档:https://github.com/rails/turbolinks/#events

      向导:http://guides.rubyonrails.org/working_with_javascript_in_rails.html#page-change-events

      【讨论】:

        猜你喜欢
        • 2011-04-19
        • 2014-07-28
        • 2013-04-23
        • 2014-04-10
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多