pablobm pablobm - 1 year ago 45
Javascript Question

How to reliably submit an HTML form with JavaScript?

Is there a way to submit an HTML form using JavaScript that is guaranteed to work in all situations?

I elaborate. The common approach seems to be:


That is all good and well except for one thing. Fields of a form are available as attributes of
, so if there is a field with name or id "text1", it can be accessed as

This means that if an elements is called "submit" (be it its name or its id), then
will not work. This is because
won't be a method of the form, but the field with that name. Unfortunately, it's fairly common that submit buttons have a "submit" name or id.

Two examples to illustrate my point. First, the following will NOT work, because an element of the form has name "submit":

<form name="example" id="example" action="/">
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>

The following will work though. The only difference is that I have removed the name "submit" from the form:

<form name="example" id="example" action="/">
<button type="button" onclick="document.example.submit(); return false;">Submit</button>

So, is there any other way to submit an HTML form using JavaScript?

Answer Source

Create another form in JavaScript, and apply its submit() method on your original form:

        function hack() {
            var form = document.createElement("form");
            var myForm = document.example;

    <form name="example" id="example" method="get" action="">
        <input type="hidden" value="43" name="hid">
          onclick="hack();return false;"

form.submit is the reference to a fresh and clean submit method, and then you use apply(myForm) to execute it with the original form.