Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1342 Is there a way to programmatically click a submit button and ensure that the onClick event is fired?

You are here: irt.org | FAQ | JavaScript | Form | Q1342 [ previous next ]

Netscape will not execute an "noWhatever" event handler if one executes a "whatever()" method via a script. Although this limitation was true, it seems that it later versions of Netscape Navigator (e.g. 4.6) this is no longer true.

So for example document.myForm.submit() does not trigger the onSubmit() event handler, but you can handle that by invoking the form buttons click(0 method:

<script language="JavaScript"><!--
document.myForm.mySubmitButton.click();
//--></script>

If you have the following form which invokes the validate() function to validate the form prior to submission:

<script language="JavaScript"><!--
function validate(what) {
    if (what.myText.value == '') {
        alert('text field empty!');
        return false;
    }
    return true;
}
//--></script>

<form onSubmit="return validate(this)">
<input type="submit">
</form>

Then it can be adapted so that a form button can be used to first ensure the form is valid and then submit the form:

<form>
<input type="button" onClick="if (validate(this.form)) this.form.submit()">
</form>

And adapted further still to allow the same thing with a link:

<form name="myForm">
<input type="submit">
</form>

<a href="javascript:;" onClick="if (validate(document.myForm)) document.myForm.submit()">Submit</a>

The following shows an alternative approach to using the click() method, by invoking the onclick() method:

<form name="myForm">
<input name="myText" type="text">
<input name="myButton" type="button" value="Click Me!" onClick="if (validate(this.form)) this.form.submit()">
<input name="mySubmit" type="submit" value="Click Me!" onClick="return (validate(this.form))">
</form>

<script language="JavaScript"><!--
document.myForm.myButton.onclick();
//--></script>

Feedback on 'Q1342 Is there a way to programmatically click a submit button and ensure that the onClick event is fired?'

©2018 Martin Webb