The onsubmit form will not be called

Here is 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 is 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 click the Submit button, nothing happens, the page just reloads. I would like her to display a warning dialog.

+6
source share
3 answers

When you call the submit function, the submit event does not fire. This is by design, it is assumed that if you run the view from the code, you have already done the necessary verification. (Note that this is true for the HTMLFormElement#submit function; this is not necessarily true for the wrapper libraries placed around it.)

In your example, I remove the click handler on the button. This is the submit button, so just put any appropriate logic in the submit event on the form. Alternatively, if you want, call validate() as part of the click button.

+19
source

You can override the original prototype of the submit method as follows:

 HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit; HTMLFormElement.prototype.submit = function (){ this._submit(); alert('Deddy Is Great :)'); // or fire the onsubmit event manually }; 
+7
source

The onclick event of your submit button fires immediately before the onsubmit event of your form, and this disables subsequent events from spreading and firing, which causes the validate function to never fire. You can see that you are removing this.disabled=true; from my sample code.

In the docs on W3 :

A form control that is disabled should prevent any click events that are in the queue at the source of the user interaction job item.

You need to remove the click event code from the submit button and just let the function do what you need, including disabling the button. For instance:

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

JsFiddle example

+2
source

Source: https://habr.com/ru/post/957629/


All Articles