2017-02-13 81 views
0

我在這是一個部分稱爲roster_panel內呈現一個Rails應用程序的簡單形式:工作後提交停止第一次成功提交

<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

提交表單後,DOM被替換爲新的,所以on click事件綁定正在丟失。

$(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); 
    }); 
    }); 
}); 

嘗試將此事件通過父元素,它不會由JavaScript覆蓋(例如身體)結合

相關問題