使用Javascript检测取消的表单文章 [英] Detect cancelled form post with Javascript

查看:93
本文介绍了使用Javascript检测取消的表单文章的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个具有很多抽象的Web项目 - 很多代码在视图模板,公司内部JavaScript库等中被松动。



我被要求劫持表单提交按钮以在表单提交时禁用它们,以禁止额外的点击。问题是,我仍然需要提交按钮,因为它在我们系统的99%中用作表单输入(不是最佳实践,但我没有编写该代码!)

我所做的是当用户点击保存时,使用jQuery隐藏了该按钮,并将一个精灵和一个微调图标禁用的副本置于其位置:

  function showSpinningButton(button){
$(button).hide();

clone = $(button).clone();

clone.prop('disabled',true);

$(button).parent()。append(clone);
clone.show();
}

这适用于标准用例,但小生例是验证 - 在那里我无法检测到表单无效并且按钮需要重置为标准。这是非常麻烦的,因为所有的验证都是在我不允许修改的面向外部的Javascript库中完成的。

要点是:是否有一个DOM事件在被提交的表单被取消(即onclick =return false;)时被解雇附加处理程序以重置按钮?

解决方案

您可以在验证函数中使用包装器:

  var oldHandler = form.prop(onsubmit); 
form.removeProp(onsubmit)。submit(function(e){
var result = oldHandler.call(this,e);
if(result == false){
//重置您的按钮
}
返回结果;
});


I'm working on a web project that has a lot of abstraction - lots of code is squirreled away in view templates, internal company javascript libraries, etc.

I have been asked to "hijack" the form submit buttons to disable them when the form is submitted, to disallow extra clicks. The problem is, I still have to submit the button as it's used in 99% of our system as a form input (not best practices, but I didn't write that code!)

What I have done is when the user clicks "Save," that button is hidden using jQuery and an exact duplicate that is disabled with a spinner icon is put in its place:

function showSpinningButton(button){
    $(button).hide();

    clone = $(button).clone();

    clone.prop('disabled', true);

    $(button).parent().append(clone);
    clone.show();
}

This works in the standard use case, but the niche case is validation - there is no way for me to detect when the form is invalid and the button needs to be reset to standard. This is especially troublesome as all the validation is done in external-facing Javascript libraries that I am not allowed to modify.

The gist is this: is there a DOM event that is fired when a form that had been submitted is cancelled (i.e. onclick="return false;") that I could attach a handler to to reset the button?

解决方案

You may use a wrapper on the validation function:

var oldHandler = form.prop("onsubmit");
form.removeProp("onsubmit").submit(function(e) {
  var result = oldHandler.call(this, e);
  if (result == false) {
    // reset your button
  }
  return result;
});

这篇关于使用Javascript检测取消的表单文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆