2012-09-26 55 views
0

我想打在我的網站上確認所有的設置形式的改變被保存,有點像Facebook並如果您在一個形式的變化,然後嘗試離開,而不保存。所以我禁用了表單上的提交按鈕,只有在值發生變化時才啓用。然後,我提示用戶在他們離開頁面之前點擊保存,以防他們有待更改。jQuery的表單驗證,並提交上變化

​​

其中一種形式需要一些額外的驗證,我使用jQuery.validate庫。例如如果我想確保用戶無法通過加倍對提交或諸如此類雙擊提交事故形式(有問題的實際驗證是一個信用卡的形式,而不是這種簡單):

$('form').validate({ 
    submitHandler: function(form) { 
    $(':submit', form).attr('disabled','disabled'); 
    form.submit(); 
    } 
}); 

不幸兩位都試圖綁定到提交按鈕,他們互相干擾等的提交按鈕保持禁用不管我做什麼,這是不可能在所有提交表單。

是否有某種方式來鏈驗證了還是怎麼了?或者以其他方式避免重寫驗證碼來重複「您是否改變了表單中的任何內容」業務?

+0

jQuery的不來了'validate'方法,您使用的這些插件? – rennat

+0

http://docs.jquery.com/Plugins/Validation – Bee

回答

0

不知道什麼地方錯了你的解決方案,但這裏有一個,似乎工作:

<!doctype html><!-- HTML5 ROCKS --> 
<html> 
<head> 
<title>Usable Forms</title> 
</head> 
<body> 

<form id="my_form" action="http://www.google.com/search"> 
    <input type="text" name="query"> 
    <input type="submit" disabled> 
</form> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"> 
</script> 
<script> 
var my_form = $('#my_form'); 
var original_form_values = my_form.serialize(); 

// Returns true if the contents of #my_form have changed since the page was 
// loaded. 
function MyFormChanged() { 
    return my_form.serialize() != original_form_values; 
} 

var submitting = false; 

// Warn of unsaved changes if the user tries to navigate away. 
window.onbeforeunload = function() { 
    // Don't stop the submission. 
    if (submitting) { 
    return; 
    } 

    if (MyFormChanged()) { 
    return 'You have unsaved changes.'; 
    } 

    // Not submitting, nor has form changed; 
    // therefore, it is safe for the user to navigate away. 
} 

$('#my_form').on('submit', function() { 
    // Just in case submit button isn't disabled for some reason. 
    $('#my_form input[type=submit]').attr('disabled', ''); 

    if (!MyFormChanged()) { 
    return false; 
    } 

    if (submitting) { 
    return false; 
    } 

    submitting = true; 
    return true; 
}); 

// Toggle submit button, depending on whether there are any changes to submit. 
$('#my_form input').on('change keyup', function() { 
    if (!submitting && MyFormChanged()) { 
    // Enable submit button. 
    $('#my_form input[type=submit]').removeAttr('disabled'); 
    } else { 
    // Disable submit button. 
    $('#my_form input[type=submit]').attr('disabled', ''); 
    } 
}); 
</script> 

</body> 
</html>