How can I submit a form using JavaScript?
Asked Answered
D

13

297

I have a form with id theForm which has the following div with a submit button inside:

<div id="placeOrder"
     style="text-align: right; width: 100%; background-color: white;">
    <button type="submit"
            class='input_submit'
            style="margin-right: 15px;"
            onClick="placeOrder()">Place Order
    </button>
</div>

When clicked, the function placeOrder() is called. The function changes the innerHTML of the above div to be "processing ..." (so the submit button is now gone).

The above code works, but now the problem is that I can't get the form to submit! I've tried putting this in the placeOrder() function:

document.theForm.submit();

But that doesn't work.

How can I get the form to submit?

Decoteau answered 24/3, 2012 at 21:10 Comment(5)
I take it you have a <form> tag someplace on your page.Collodion
I don't see any <form> in the code.Telestich
what do you mean by : The function changes the innerHTML of the above div to be "processing ..." (so the submit button is now gone). and would you mind to share that logic . By the way if you have an submit button (somewhere down with name=submit ) , the theform.submit() function will not work . Please clarify you question by adding <form> tag as you have in your code . You might use jsfiddle.netStreaky
...if you have an submit button (somewhere down with name=submit )... This solved my problem! It was <input type="button" name="submit" ..., but still blocking the javascript from sending the form.Glisson
document.theForm.submit(); doesn't work, you'd rather need to use document.getElementById("theForm").submit(); and specify the form id in HTML, for example: <form id="theForm">(content)</form>Conjugated
A
193

Set the name attribute of your form to "theForm" and your code will work.

Appaloosa answered 24/3, 2012 at 21:12 Comment(2)
This may seem super-obvious to some, but i had a button with the name and id "submit", and document.theForm.submit() reported an error. Once I renamed my button, the code worked perfectly.Vitascope
@Vitascope What is the name of button you had? Coz, as per api.jquery.com/submit child elements of a form should not use input names or ids that conflict with properties of a form.Hobo
G
183

You can use...

document.getElementById('theForm').submit();

...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);
Genital answered 24/3, 2012 at 21:12 Comment(5)
How do you tell it where to send the form? For example, in my case, I want the content emailed to meCongeal
@Imray You'll probably want server-side code to do that for you.Genital
@Congeal set action="/{controller}/{action-method}" method="post" attributes of the form you are trying to post.Rayerayfield
as my form name is printoffersForm as well as id is same. document.getElementById('printoffersForm').submit(); but i gives me error submit is not an functionBassist
@MadhuriPatel Could be you have your submit button also named submit? See answer #833532Foreigner
A
56

It works perfectly in my case.

document.getElementById("theForm").submit();

Also, you can use it in a function as below:

function formSubmit()
{
    document.getElementById("theForm").submit();
}
Ascensive answered 29/3, 2013 at 12:17 Comment(5)
will this submit form values from an input tag?Alis
@roy Yes, it will submit form values from input tags.Ascensive
@ChintanThummar and then you can handle the Form submit using document.getElementById("form1").onsubmit = function(){ //You can use Ajax Code here to submit the form // without refreshing page }Dorton
Please take into account that, in the OP's example, the form id is called theForm, something they have written on the very first line of their question, but that surprisingly was 'forgotten' (or ignored) by half the answers here, no matter how correct they are.Fertility
Thanks @GwynethLlewelyn to point it out. It's updated now.Ascensive
C
26
document.forms["name of your form"].submit();

or

document.getElementById("form id").submit();

You can try any of this...this will definitely work...

Chapfallen answered 28/5, 2014 at 5:16 Comment(2)
In order to get the first one to work I had to change it to document.forms.namedItem("FormName").submit();Judge
Please take into account that the OP told us the form id — it's called theForm in their example — so you could perhaps change your answer to reflect that?Fertility
L
15

I will leave the way I do to submit the form without using the name tag inside the form:

HTML

<button type="submit" onClick="placeOrder(this.form)">Place Order</button>

JavaScript

function placeOrder(form){
    form.submit();
}
Lorenelorens answered 18/4, 2017 at 8:11 Comment(2)
I suggest adding type="button" in the HTML part. Otherwise the button will e.g. submit in a form.Riggle
1. Technically, I think you could just do <button type="submit" onClick="this.form.submit()">Place Order</button> and save a function call. 2. @KenJiiii I would have to look it up, but my guess is that, if this button is outside the form, it won't submit anything except via JavaScript. Nevertheless, your suggestion is appropriate — because someone might make a mistake, forget to close with </form>, and then there will be unexpected results. 3. I'm not quite sure if you can get this.form to work in all scenarios, especially on deeply-nested HTML5.Fertility
A
15

You can use the below code to submit the form using JavaScript:

document.getElementById('FormID').submit();
Arran answered 30/1, 2018 at 14:9 Comment(1)
'theForm' is the actual form id, according to the OP. You may wish to change your line of code to reflect that.Fertility
A
14
<html>

    <body>

        <p>Enter some text in the fields below, and then press the "Submit form" button to submit the form.</p>

        <form id="myForm" action="/action_page.php">
          First name: <input type="text" name="fname"><br>
          Last name: <input type="text" name="lname"><br><br>
          <input type="button" onclick="myFunction()" value="Submit form">
        </form>

        <script>
            function myFunction() {
                document.getElementById("myForm").submit();
            }
        </script>

    </body>
</html>
Armorial answered 29/3, 2018 at 8:25 Comment(3)
This answer might be helpful for some https://mcmap.net/q/101950/-html-beginform-with-html-attributes-asp-net-mvc4Gensmer
@MayerSpitz I can't quite understand how that relates to this answer?...Fertility
It's another approach of form creation using razor, I found it very structured and greatly usefulGensmer
J
5

HTML

<!-- change id attribute to name  -->

<form method="post" action="yourUrl" name="theForm">
    <button onclick="placeOrder()">Place Order</button>
</form>

JavaScript

function placeOrder () {
    document.theForm.submit()
}
Jehias answered 5/8, 2016 at 6:9 Comment(3)
This does not improve the quality of the answers that are already given.Gonzalez
It's the only answer that shows the form name in the actual html for the form definition. Also, it's simple and straightforward.Caves
Hmm. I think that this would only work if this form is at the 'root' of the DOM (as in very simple & trivial pages with zero nesting levels). I could do some testing, but I believe it's pointless, there are better solutions than this one.Fertility
O
4

If your form does not have any id, but it has a class name like theForm, you can use the below statement to submit it:

document.getElementsByClassName("theForm")[0].submit();
Ornas answered 7/1, 2015 at 17:11 Comment(2)
what about there are more forms with the same class name above?Pace
@Pace With this answer, only the first form would be submitted, all others would be silently ignored.Fertility
B
1
let form = document.getElementById('theForm');
let div = document.getElementById('placeOrder');
let span = document.createElement('span');
form.addEventListener('submit', function(e){
    e.preventDefault(); 
    div.style.display = 'none';
    span.innerText = 'processing...';
    form.appendChild(span);

    console.log('form is submitted.');
})

This is how you should approach this issue This answer is for new developers who kind of face this kind of issue.

Bors answered 27/8, 2023 at 9:41 Comment(1)
See my comments on your other answer!Fertility
B
1

I know this is very old question but this might help some new developers There are multiple ways to get this form working but here is a simple tweak Here is the code

<form action="/" class="form" id="theForm">
            <div id="placeOrder"
                style="text-align: right; width: 100%; background-color: white;">
                <button type="submit"
                        class='input_submit'
                        style="margin-right: 15px;"
                        onclick="placeOrder()">Place Order
                </button>
            </div>
        </form>

<script>
function placeOrder(){ 
            let form = document.getElementById('theForm');
            let div = document.getElementById('placeOrder');
            let span = document.createElement('span');
            span.innerText = 'Processing...';
            document.querySelector('button.input_submit').style.visibility = 'hidden';
            div.appendChild(span);
        }
</script>
Bors answered 13/3 at 6:37 Comment(1)
I like your complete answer best; maybe you should delete the other one, which is not so carefully written? Thanks!Fertility
G
0

I have came up with an easy resolve using a simple form hidden on my website with the same information the users logged in with. Example: If you want a user to be logged in on this form, you can add something like this to the follow form below.

<input type="checkbox" name="autologin" id="autologin" />

As far I know I am the first to hide a form and submit it via clicking a link. There is the link submitting a hidden form with the information. It is not 100% safe if you don't like auto login methods on your website with passwords sitting on a hidden form password text area...

Okay, so here is the work. Let’s say $siteid is the account and $sitepw is password.

First make the form in your PHP script. If you don’t like HTML in it, use minimal data and then echo in the value in a hidden form. I just use a PHP value and echo in anywhere I want pref next to the form button as you can't see it.

PHP form to print

$hidden_forum = '
<form id="alt_forum_login" action="./forum/ucp.php?mode=login" method="post" style="display:none;">
    <input type="text" name="username" id="username" value="'.strtolower($siteid).'" title="Username" />
    <input type="password" name="password" id="password" value="'.$sitepw.'" title="Password" />
</form>';

PHP and link to submit form

<?php print $hidden_forum; ?>
<pre><a href="#forum" onClick="javascript: document.getElementById('alt_forum_login').submit();">Forum</a></pre>
Gladis answered 2/2, 2016 at 20:40 Comment(4)
True you need to submit form but the link wont appear in my coding sorry but make a onclick or href=javascript: document.getElementById('alt_forum_login').submit()Gladis
The question is about javascript, there's no need for the php code at allCoincident
1. I have to strongly discourage anybody from using something like this: Sending your passwords in clear text to the browser is a HUGE security flaw. 2. This response doesn't relate to the question Your effort to provide help is appreciated! But please be more careful around security topics. It's tempting for many to copy solutions from stackoverflow without fully understanding them.Polad
This is the worst possible security flaw ever. DO NOT USE THIS ANSWER. For the sake of @Gladis — "hiding" the form just hides it from the user, but not from the browser, and it's trivially simple to see the name & password. You're not really "hiding" anything there.Fertility
L
0

If you land here looking for the best way to submit a form using a button outside the form:

As of HTML5, just use the button's form attribute.

<button type="submit" form="my_form_id">Submit</button>

This method can submit forms in unique contexts (eg: Stripe's iframe based PaymentElement) that JS inline onClicks won't work with.

Submit form using a button outside the <form> tag

Leeannaleeanne answered 2/3, 2023 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.