jQuery form submit vs document.form.submit

ddallala picture ddallala · Jan 21, 2011 · Viewed 9.5k times · Source

I have the following form:
<form name="dealerLocatorForm"method="post"action="result.php">...</form>

I have attached the Omniture SiteCatalyst formAnalyis plugin to it, which is supposed to send back information only when the form was NOT submitted.

The expected behavior: when a form is submitted using a submit button NO beacon should be fired (because things went as expected).

Problem:
The form needed some validation so the developers decided to programmatically submit the form using: document.form.dealerLocatorForm.submit() or document.dealerLocatorForm.submit()

However, when the form is submitted this way, the plugin fires a beacon informing me that the form was not submitted ALTHOUGH IT WAS.

On the other hand if I use jQuery to submit as so: jQuery('form[name=dealerLocatorForm]').submit()
the form is CORRECTLY submitted and the beacon does not fire !

In short jQuery is successfully replicating all the functionalities of a form submit as if it were submitted by a Submit Button while the document.form submit is not.

So my question is: What is the difference between:
document.form.dealerLocatorForm.submit()
document.dealerLocatorForm.submit()
and
jQuery('form[name=dealerLocatorForm]').submit()

It seems as though jQuery is doing something more accurate.

Answer

Justin M. Keyes picture Justin M. Keyes · Jul 28, 2011

The behavior of this syntax is non-standard and not consistent across browsers:

document.form.dealerLocatorForm.submit()
document.dealerLocatorForm.submit()

Use getElementById() instead (which is what jQuery uses internally):

document.getElementById("dealerLocatorForm").submit()

Make sure you have the id attribute set on your form element:

<form id="dealerLocatorForm" ... >