2015-09-07 69 views
-2

我確定對此有一個簡單的解釋,但在搜索答案時我找不到正確的單詞。表單在動態更改類時提交錯誤的函數

當用戶填寫表單.InvoiceForm時,它通過Ajax提交。提交後,請移除.InvoiceForm類並添加.UpdateInvoice。當用戶提交.UpdateInvoice表單時,它說明他們即將進行更改,並且他們必須點擊說「是的,我希望更新」。

問題是,除非我刷新頁面以便窗體使用.UpdateInvoice窗體加載,否則我不會收到確認信息,這意味着它仍然以.InvoiceForm窗體的形式提交。有什麼我可以解決這個問題嗎?

編輯,顯示代碼:運行如果沒有記錄在運行,如果有更新

$('.UpdateInvoice').submit(function(){ 

     var r = confirm("Are you sure you want to make this update?"); 
     if (r == true) { 
      $.ajax({ 
      url: $(this).attr('action'), 
      type: 'POST', 
      cache: false, 
      dataType: 'json', 
      context: this, 
      data: $(this).serialize(), 
      beforeSend: function() { 
       $(".validation-errors").hide().empty(); 
      }, 
      success: function(data) { 

       alert('This row has been updated'); 
       $(this).find('.total').html(data); 
      } 
     }); 
     } else { 

     } 
     return false; 
    }); 

爲.UpdateInvoice沒有按功能的記錄

$('.InvoiceForm').submit(function(e) { 

     $.ajax({ 
      url: $(this).attr('action'), 
      type: 'POST', 
      cache: false, 
      dataType: 'json', 
      context: this, 
      data: $(this).serialize(), 
      beforeSend: function() { 
       $(".validation-errors").hide().empty(); 
      }, 
      success: function(data) { 
       $(this).removeClass('InvoiceForm'); 
       $(this).addClass('UpdateInvoice'); 
       $(this).find('.btn').val('Update'); 
       $(this).find('.id').val(data.invoice_id); 
       $(this).find('.btn').removeClass('btn-default'); 
       $(this).find('.btn').addClass('btn-danger'); 
       $(this).find('.AddRow').removeClass('hide'); 
       $(this).find('.invoiceDetails').html(data.returnedData); 
       $(this).parent().next().find('.grade').focus(); 

      } 
     }); 
     return false; 
}; 

代碼

代碼除非我刷新頁面,否則不會運行。

感謝您的幫助。

+1

帖子相關代碼 – Coderchu

+0

你需要提供你一直試圖做一個代碼示例。 – KrakenDev

+0

這聽起來像是在頁面加載時運行JavaScript來設置確認。但是,如果頁面加載時UpdateInvoice表單不存在,它將無法設置確認。將UpdateInvoice表單添加到頁面後,您需要執行該代碼。如果你顯示你的代碼,有人可以幫助你。 –

回答

0

您在創建「.UpdateInvoce」之前綁定了單擊事件,因此它不起作用。我認爲你需要使用.live()才能使它工作。在這裏看到的文檔:jQuery's live()

HTML:

<button id="click_me" class="new">Click Me</button> 
<div class="result" /> 

腳本:

$(function() { 
    $('.new').click(function (e) { 
     $('.result').text("Im new !"); 
     $(this).removeClass("new"); 
     $(this).addClass("update"); 

     // Bind UpdateInvoice's click event on the fly 
     $('.update').live(bindUpdate()); 
    }); 

    function bindUpdate() { 
     $('.update').click(function (e) { 
      $('.result').text("Update me !"); 
     }); 
    } 
}); 

jsfiddle's demo

+0

on()與live()做同樣的事情嗎?它說live()已被折舊。 – QuickBen

+0

是的,請參閱更新的演示:https://jsfiddle.net/2gankv79/1/ – RyanB