0

我想让我网站上的所有设置表单确认更改已保存,有点像 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();
  }
});

不幸的是,这两个位都试图绑定到提交按钮,并且它们相互干扰,因此无论我做什么,提交按钮都保持禁用状态,根本不可能提交表单。

有什么方法可以将验证链接在一起吗?或者其他方式来避免重写验证代码以重复“您是否更改了表单中的任何内容”业务?

4

1 回答 1

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>
于 2012-09-27T02:34:44.757 回答