简体   繁体   中英

Stop form submit from javascript

I have prepared this demo for the problem http://jsfiddle.net/20k4ur8o/

As you can see when you try to submit the form via the input it is stopped but when you click the button the form submits. How can I prevent the form from submitting when .submit() is called without overwriting the default behavior of the function, because I need to also keep other submit listeners active when it is called?

HTML

<form action=test id=form>
    <input type=submit>
</form>
<button id=submit>Submit</button>

JS

document.getElementById('form').addEventListener('submit', function (e) {
    e.preventDefault();
    alert('stopped');
}, false);

document.getElementById('submit').onclick = function () {
    document.getElementById('form').submit();
}

You could do something like this:

(function() {
  var form = document.getElementById('form');
  var submit = form.submit;

  form.submit = function() {
    var evt = new Event('submit', {
      cancelable: true
    });

    form.dispatchEvent(evt);

    //minimc the default behaviour and submit the form if 'preventDefault'  was not called.
    if (!evt.defaultPrevented) {
      submit.call(form);
    }
  };
}());

But be award that this might result in memory leaking in older browsers.

EDIT Update the code to include Event emitting. This is only tested in latest WebKit/BLINK and FireFox. For IE and older browser you might need a fallback.

Updated fiddle

EDIT 2
You should maybe think about another solution, eg something like this:

function submitCallback(e) {
    e.preventDefault();
    alert('stopped');
}    

document.getElementById('form').addEventListener('submit', submitCallback, false);

formPreventSubmit(document.getElementById('form'), submitCallback);


function formPreventSubmit(form, submitCallback) {
  var submit = form.submit;

  form.submit = function() {
    var evt = new SomeCustomEvent();

    submitCallback(evt)

    if (!evt.defaultPrevented) {
      submit.call(form);
    }
  };
}

SomeCustomEvent need to be some class that mimics the behavior of a real event having a preventDefault function.

document.getElementById('submit').onclick = function () {
  document.getElementById('form').submit(function(e) {
    alert( "Handler for .submit() called." );
    e.preventDefault();
  });
}

EDIT: My mistake, I misread your question. You just need to bind an event listener to the submit method and run the same preventDefault method.

http://api.jquery.com/submit/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM