2

I have a form like:

<form method="POST" action="page.html" onsubmit="alert('foo'); // validate();" name="foobar">
...
</form>

and a link like:

<div onclick="document.foobar.submit();">click me</div>

How can I capture the submit() method and call my validate function?

JsBin example

Steffen Maas
  • 23
  • 1
  • 3

4 Answers4

1

You can call method from html itself. modified jsbin. Instead of submitting form on click you can call submitHandler and pass form reference.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
  <script type="text/javascript">
    function validate(){

    }

    function submitHandler(form){
      validate();
      alert('foo');

}
    window.onload = function(){
        document.foobar.submit = submitHandler;
    }
</script>

</head>
<body>
    <form method="POST" action="page.html" onsubmit="submitHandler(this);" name="foobar">
      <input type="text" />
    </form>

    <div onclick="document.foobar.submit()">click me</div>
</body>    
</html>
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

Uniquely identify your form with an id

document.getElementById('formid').onsubmit = function() {
    // You have captured the submit method now do what you need
};

Demo

Starx
  • 77,474
  • 47
  • 185
  • 261
  • @SteffenMaas, There was a typo in my code. And you are suppose to catch the submit event being triggered, not the execution of submit function. – Starx Oct 10 '12 at 12:06
  • I tryed your Demo in FF and Opera, but when I hit the 'click me' link, the alert does not show up. – Steffen Maas Oct 10 '12 at 12:14
  • @SteffenMaas, Use the submit button to see the alert box. About the link not triggering the submit, I am puzzled at that myself. – Starx Oct 10 '12 at 12:15
  • Follow [this](http://stackoverflow.com/questions/12819357/form-submitted-using-submit-from-a-link-cannot-be-caught-by-onsubmit-handler) question to know why `onclick` is not working. – Starx Oct 10 '12 at 12:36
  • Ok, with the a click on the submit button, I see the alert box. I'm curious about your solution about trigging the event. :) – Steffen Maas Oct 10 '12 at 12:37
  • Oh, sorry a misunderstanding. :) – Steffen Maas Oct 10 '12 at 12:59
0

You could use the jQuery .submit() handler.

$('form').submit(function(evt) {
  evt.preventDefault();
  alert('Handler for .submit() called.');
  // Validate function returns false or true
});
David
  • 435
  • 4
  • 8
0

Try this:

<script type="text/javascript">
function addEventsToHTML(){
    var form = document.getElementById('foobar');
    form.onsubmit = submitHandler;
    function submitHandler(){
        validate();
    }
}
window.onload = addEventsToHTML;
</script>
Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47