2011-05-20 81 views
0

我有一張客戶表,每行都有一個方法,彈出一個內聯表單,顯示客戶的詳細信息。在這個頁面上還有一個搜索,一些標籤和一些href鏈接&函數。jQuery - 防止提交未保存的表單

我想要做的是防止用戶能夠將此表單保留在未保存的狀態。所以我有一個變量formChanged設置爲TRUE表單輸入更改或粘貼。如果formChanged == true,那麼我不希望用戶能夠點擊鏈接或執行搜索,直到他們確認是否保存數據。

我使用以下,以提示用戶:

$(document).click(function(eve) { 
    if (!$(eve.target).is('#form *')) { 
     if (formChanged) { 
      if (confirm("Do you want to save the data or continue to edit?")) { 
        $('#form').submit(); 
        return true; 
       } 
      else { return false; } //here I do not want to submit the form OR continue with the openForm() method; 
     } 
    } 
}); 

HTML標記(簡化的)是這樣的:

<a href="/new">New Customer</a> 
<a href="javascript:performSearch();">Search</a> 
<table> 
    <tr> 
     <td onclick="openForm(1);">Customer One</td> 
    </tr> 
    <tr> 
     <td onclick="openForm(2);">Customer Two</td> 
    </tr> 
    <tr> 
     <td><form> //form gubbins loaded via ajax in here </form></td> 
    <tr> 
     <td onclick="openForm(2);">Customer Two</td> 
    </tr> 
</table> 

我有被我可以捕獲確認邏輯的問題,但其他功能,如openForm & performSearch()仍然繼續執行。

理想情況下,我想只運行功能/跟隨URL如果用戶選擇保存,並且如果用戶按下CANCEL,則不執行任何操作。

顯而易見的解決辦法是把在的OpenForm和performSearch功能這個邏輯,但是這是一個非常簡化的示例,作爲真正的頁面有幾十種不同的功能,這是在許多網頁共享,因此,這是不是真的有可能

回答

0

你可能想是這樣的:Javascript - Confirmation when leaving page

而是在代碼的最後一節的if(disabledConfirm_exit) return;的,檢查formChanged變量。

在jQuery的 - 你可以這樣做:http://api.jquery.com/unload/

+0

可是如何才能讓。卸載在showForm()函數中執行,類似於這樣的操作。$('#form')。remove(); //卸載應該在這裏調用,但似乎沒有? $('tr#id')。load('getform.php');' – danielc 2011-05-20 02:20:21

0

更新

我不知道是否有一個更好的模式或者一些你可能能夠使用,但直到其他人發佈的現有方法更好的答案,這是我的。你可以編寫一個委託方法,它將在任何地方調用,並且作爲參數,將被賦予被調用的函數和該函數的參數。它可以檢查表單是否已經更改 - 如果沒有,它會調用相應的功能,否則會提示用戶。事情是這樣的:

<a href="/new">New Customer</a> 
<a href="javascript:check(performSearch);">Search</a> 
<table> 
    <tr> 
     <td onclick="check(openForm,1);">Customer One</td> 
    </tr> 
    <tr> 
     <td onclick="check(openForm, 2);">Customer Two</td> 
    </tr> 
    <tr> 
     <td><form> //form gubbins loaded via ajax in here </form></td> 
    <tr> 
     <td onclick="check(openForm, 2);">Customer Two</td> 
    </tr> 
</table> 

check功能看起來是這樣的(在它的當前形式,它是真正簡單,只有一個參數適用於將要調用的功能,但它可以作出更通用):

function check(func, param){ 
    if (!formChanged){ 
     func(param); //invoke the original function 
    } 
    else{ 
     //handle the case for a modified form that the user wants to leave 
    } 
} 

,如果你連接通過JavaScript的事件處理程序,而不是在HTML中指定它們你也許可以做到這一點更清潔的方式 - 不顯眼的JavaScript從行爲中分離標記的宗旨


這聽起來像你正在尋找window.onbeforeunload

+0

這不好,因爲一切都是通過Ajax,所以窗口不會「卸載」? – danielc 2011-05-20 02:25:45

+0

@IIBCDaniel你說得對,我錯過了。我沒有一個我知道是正確的/好的答案,但是我發佈了一些可能有用或沒用的答案。 – 2011-05-20 05:12:41