Form 'onsubmit' not getting called
Solution 1:
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
.
Solution 2:
You can override the original prototype "submit" method like this:
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = function (){
this._submit();
alert('Deddy Is Great :)'); // or fire the onsubmit event manually
};
Solution 3:
The onclick event of your submit button is firing immediately before the onsubmit event of your form, and this is disabling subsequent events from propagating and firing, which causes the validate function to never get triggered. You can see this is you remove the this.disabled=true;
from your code example.
Per the docs at W3:
A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.
You should remove the click event code from the submit button, and simply allow the function to do what you need it to do, including disabling the button. For example:
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