提交在首次成功提交后停止工作

时间:2017-02-13 05:24:50

标签: javascript jquery ruby-on-rails turbolinks

我在rails app中有一个简单的表单,它在一个名为roster_panel的部分中呈现:

<div id = 'active_admin_content'>
  <%= semantic_form_for @roster_item do |form| %>
      <h3>Add a counselor</h3>
      <div id="counselor_status_message"><%= @status_message %></div>
      <%= form.inputs do %>
          <%= form.input :first_name, input_html: {id: 'counselor_first_name'} %>
          <%= form.input :last_name, input_html: {id: 'counselor_last_name'} %>
          <%= form.input :email, input_html: {id: 'counselor_email'} %>
      <div class="button_container" >
        <input id="submit_counselor_add" type="button" value = "Send forms packet" class = "button" >
      </div>
      <% end %>
  <% end %>
</div>

在我的jquery代码中,我将提交点击绑定到:

$( document ).on('turbolinks:load', function() {
    $("#submit_counselor_add").click(function(){
        $.get("add_counselor_info" , { id: $("#roster_id").text(), first_name: $("#counselor_first_name").val(),
                last_name: $("#counselor_last_name").val(), counselor_email: $("#counselor_email").val() },
            function(data){ $("#roster_panel").html(data);
            }
        )
    });
});

这路由到此控制器方法:

def add_counselor_info
  @roster = Roster.find(params[:id])
  @group = ScheduledGroup.find(@roster.group_id)
  @liaison = Liaison.find(@group.liaison_id)
  @items = RosterItem.where(roster_id: @roster.id)
  @roster_item = RosterItem.new(group_id: @group.id, roster_id: @roster.id,
                                first_name: params[:first_name], last_name: params[:last_name],
                                email: params[:counselor_email], youth: false, item_status: 'Unconfirmed' )
  if @roster_item.save
    @error_count = 0
    @status_message = 'This counselor has been added and the forms package has been emailed. You may enter another counselor.'
    @items = RosterItem.where(roster_id: @roster.id)
    @roster_item = RosterItem.new
  else
    @error_count = @roster_item.errors.size
    @status_message = "#{@error_count} errors prevented saving this information: "
    @roster_item.errors.full_messages.each { | message | @status_message << message << ' '}
    @items = RosterItem.where(roster_id: @roster.id)
  end
  render partial: 'roster_panel'

在加载新页面后,此过程正常工作并按预期重新显示表单。但是,此时提交按钮不再触发jquery中的操作。但是,页面上的其他jquery函数仍然有效。这可能与turbolinks有关,我不太熟悉。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

提交表单后,DOM将被新的替换,因此on click事件绑定正在丢失。

尝试通过父元素绑定此事件,该元素不会被javascript覆盖(例如正文):

$( document ).on('turbolinks:load', function() {
  $("body").on('click', '#submit_counselor_add', function() {
    $.get("add_counselor_info", { 
      id: $("#roster_id").text(), 
      first_name: $("#counselor_first_name").val(),
      last_name: $("#counselor_last_name").val(), 
      counselor_email: $("#counselor_email").val() 
    },function(data) { 
      $("#roster_panel").html(data);
    });
  });
});