Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form 'onsubmit' not getting called

Here's the part of my form:

<form name='form-main' onsubmit='return validate()' action='' method='post'>
    <center><input type='submit' onClick='this.disabled=true; this.form.submit();' value='I accept - Download the GM!'/></center>
</form>

and here's the validate function:

function validate()
{
    // this is just to test if it actually shows
    alert('You must not leave any of the fields blank!');
    return false;
}

Whenever I hit the submit button, nothing happens, the page just reloads.. I would like it so it shows the alert dialog.

like image 847
user1667191 Avatar asked Nov 07 '13 21:11

user1667191


People also ask

Why Onsubmit is not being called?

The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled.

What happens when Onsubmit returns false?

It means that do nothing on submit.

How do you call a function Onsubmit?

You can put your form validation against this event type. The following example shows how to use onsubmit. Here, we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.


1 Answers

When you call the form's submit function, the submit event is not fired. This is by design, the assumption is that if you're triggering the submission from code, you've already done any necessary validation. (Note that this is true of the HTMLFormElement#submit function; it is not necessarily true of the wrappers libraries put around it.)

In your example, I would remove the click handler on the button. It's a submit button, so just put any relevant logic in the submit event on the form. Alternately, if you prefer, call validate() as part of the button's click.

like image 52
T.J. Crowder Avatar answered Oct 08 '22 02:10

T.J. Crowder