Detect cancelled form post with Javascript

女生的网名这么多〃 提交于 2020-01-15 03:14:08

问题


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?


回答1:


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;
});


来源:https://stackoverflow.com/questions/24959843/detect-cancelled-form-post-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!