Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...