我希望在我的网站上设置我的所有设置表单确认更改已保存,如果您在表单中进行更改,然后尝试导航而不保存,则有点像facebook。因此,如果值发生变化,我只会启用表单上的“提交”按钮。然后,我提示用户在他们离开页面之前点击保存,以防他们确实有待更改。
var form = $('form.edit');
if(form.length > 0) {
var orig_str = form.serialize();
$(':submit',form).attr('disabled','disabled');
form.on('change keyup', function(){
if(form.serialize() == orig_str) {
setConfirmUnload(false);
$(':submit',form).attr('disabled','disabled');
} else {
setConfirmUnload(true);
$(':submit',form).removeAttr('disabled')
}
});
$('input[type=submit]').click(function(){ setConfirmUnload(false); });
}
function setConfirmUnload(on) {
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
return 'If you navigate away from this page without saving your changes, they will be lost.';
}
这些表单中的一个需要一些额外的验证,我使用jQuery.validate库。例如如果我想确保用户不能通过双击提交或某些事情来重复提交表格(有问题的实际验证是信用卡表格,而不是这么简单):
$('form').validate({
submitHandler: function(form) {
$(':submit', form).attr('disabled','disabled');
form.submit();
}
});
不幸的是,两个位都试图绑定到提交按钮,并且它们互相干扰,无论我做什么,提交按钮都保持禁用状态,根本无法提交表单。
有没有办法将验证链接在一起或什么?或者其他一些方法可以避免重写验证码重复“你在表格中做了什么改变”的事情吗?
答案 0 :(得分: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>