Submit form using a button outside the <form> tag
Asked Answered
T

15

509

Say I have:

<form method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" />

How do I go about submitting that form with that submit button outside of the form, I think in HTML5 theres an action attribute for the submit but I'm not sure if thats fully cross-browser and if it isn't is there anyway to do this?

Tusker answered 11/8, 2011 at 3:55 Comment(10)
I don't think you can do that without javascript. How will the browser know what form it is? There could be several. Why can't you put the submit button inside the form?Lopez
if you don't want to use JS then to me it looks impossible in in html(<5), just out of curiosity, why would you have such kind of arrangement in code?Incriminate
I have a multi tabbed settings area with a button to update all, due to the design of it the button would be outside of the form. I'm just going to roll with the HTML5 option or a JS solution as this question seems to be redundant.Tusker
@benhowdle89 - Why in the world did you go through and add YOLO to a bunch of questions? Did you walk away while logged in?Kingkingbird
@Kumar, I also thought it would be impossible, but it looks like it is not https://mcmap.net/q/73904/-submit-form-using-a-button-outside-the-lt-form-gt-tagClairvoyant
@dav, yes it seems to work, jsfiddle.net/erdt761h, didn't check on multiple browsers...Incriminate
Do not add tags, especially javascript. The author doesn't want it and has explicitly stated so (see comment to my answer).Rump
nowadays the answer is developer.mozilla.org/en-US/docs/Web/HTML/Element/…Evannia
@Evannia with the answer for those of us in 2018.Mezzotint
In ReactJS you probably can use ReactPortalsEligible
V
97

Update: In modern browsers you can use the form attribute to do this.


As far as I know, you cannot do this without javascript.

Here's what the spec says

The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls.

That's my bold

A submit button is considered a control.

http://www.w3.org/TR/html4/interact/forms.html#h-17.2.1

From the comments

I have a multi tabbed settings area with a button to update all, due to the design of it the button would be outside of the form.

Why not place the input inside the form, but use CSS to position it elsewhere on the page?

Verminous answered 11/8, 2011 at 4:9 Comment(7)
FYI, HTML5 support, not perfect yet but it's getting there: impressivewebs.com/html5-form-attributeMissymist
I am a bit late here, but how can you put the input in the form, but position it somewhere else?Zip
You can use <button> tag for this purposes for html4Sclerosis
The answer is no longer valid, as Joe the Squirrel's answer works - as of 2016.Cyano
there is a concern with the JavaScript solutions proposed. in the latest Chrome for example, HTML5 validation (required, etc.) is skipped. one solution i can think of is having two submit buttons, one hidden. a click should be triggered on the hidden button. the form should not be submitted without proper validation.Piscatelli
right after this comment, i discovered form.checkValidity() and form.reportValidity() which are not supported in Edge : )Piscatelli
thanks! now i can have a submit button outside form in modalsFarrington
A
982

In HTML5, there is the form attribute. Basically

<form id="myform" method="get" action="something.php">
    <input type="text" name="name" />
</form>

<input type="submit" form="myform" value="Update"/>
Analgesia answered 24/9, 2012 at 14:56 Comment(9)
This doesn't work on IE for anyone who plans to use it. I used it but then decided to add submit event function callback to manually submit the form on IE browsers.Mentor
Which IE versions exactly?Wengert
I did this as a graceful fallback: <button type="submit" form="frmFoo" onclick="!this.form&&$('#'+$(this).attr('form')).submit()"> As experiments revealed, this.form is the attached form DomElement, while it's null otherwise. // edit: jQuery, but possible with vanilla, too ofcSaintsimonianism
If you want to see the form attribute in MS Edge please vote here: wpdev.uservoice.com/forums/257854-microsoft-edge-developer/…Caffey
Lie, since this is a high-exposure answer on a high-exposure page, and there's the stupid "min 6 chars" edit limit: could you please fix the INPUT tags to not be self-closing? (Here's the change summary of my unsuccessful edit attempt: "Fixed invalid self-closing tag syntax for non-XHTML (but HTML5) INPUT, which is a void element (thus can't be closed).") Thanks!Leisha
@Sz: I disagree with the proposed edit. Void elements must not have a closing tag (e.g. <input></input>) and in HTML5 non-void elements aren't allowed to have solidus in the start tag, but a solidus at the end of a start tag is not invalid for void elements, it's simply ignored. The syntax in my answer is valid for both HTML5 as well as XHTML5.Analgesia
@Sz: Refer to 8.1.2.1. Start tags "if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing."Analgesia
@LieRyan, oops, thank you very much for the spec. reference, and sorry then, I was not sufficiently up-to-date about that issue!Leisha
A vanilla-JS version of @AdrianFöder fallback would be: <button type="submit" form="frmFoo" onclick="!this.form && document.getElementById('myform').submit()">Attenuant
O
370

A solution that works great for me, is still missing here. It requires having a visually hidden <submit> or <input type="submit"> element whithin the <form>, and an associated <label> element outside of it. It would look like this:

<form method="get" action="something.php">
     <input type="text" name="name" />
     <input type="submit" id="submit-form" class="hidden" />
</form>

<label for="submit-form" tabindex="0">Submit</label>

Now this link enables you to 'click' the form <submit> element by clicking the <label> element.

Olli answered 4/5, 2014 at 13:37 Comment(14)
Works in IE 11 too. I know, you don't often see "works" and "IE" in the same sentence.Fleabag
Wow, this answer is useful when creating an interface that has a submit button which is far and outside the <form>. This is a simple solution. This answer might be answer to the question. :)Triliteral
Better solution without any incompatibilities. If using Twitter Bootstrap, you can just use "btn btn-primary" for the label css class and it works perfect.Coenosarc
Very nice solution, however there might be one objection to using this method. A label is not a focusable element (AFAIK) so it's not intuitive for a user that is only using the keyboard to navigate to the 'button' and then press space to activate that button for example. (I realise you can press <enter> instead, but that's not the only way people are used to navigating forms with the keyboard)Coo
I used this solution. The only issue with it is that submit button cannot be tab selectedClerissa
Awesome trick! You can use bootstrap to stylize the label like a buttonCanonical
Please vote here if you want to see the form attribute feature in MS Edge: wpdev.uservoice.com/forums/257854-microsoft-edge-developer/…Caffey
To focus the label via tab button, you can use tabindex HTML attribute: <label for="submit-form" tabindex="0">Submit</label> as per this questionFlashover
@MarthyM, your suggestion regarding tabindex was very helpful, especially for readers who only look at the top-voted answers, so thank you. Please note, however, that @Jonathan's answer already included this feature.Catnip
Thanks for this smart workaround, for some reason I could not hide the button using the class, so set display: none; in CSS.Hetti
love this, even after 3 years. This actually triggers the input 'required' attributes, where .submit(); from outsite the form wouldn'tFermentation
After adding tabindex="0", the tab can focus on it, however when I press Enter or Space, it does not submit the form. However, Lie Ryan's way works in this case.Offside
Awesome idea to avoid the .submit() and preserve the validation.Gwenora
don't know why but I had to style="display:none" to hide itPneumonectomy
V
97

Update: In modern browsers you can use the form attribute to do this.


As far as I know, you cannot do this without javascript.

Here's what the spec says

The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls.

That's my bold

A submit button is considered a control.

http://www.w3.org/TR/html4/interact/forms.html#h-17.2.1

From the comments

I have a multi tabbed settings area with a button to update all, due to the design of it the button would be outside of the form.

Why not place the input inside the form, but use CSS to position it elsewhere on the page?

Verminous answered 11/8, 2011 at 4:9 Comment(7)
FYI, HTML5 support, not perfect yet but it's getting there: impressivewebs.com/html5-form-attributeMissymist
I am a bit late here, but how can you put the input in the form, but position it somewhere else?Zip
You can use <button> tag for this purposes for html4Sclerosis
The answer is no longer valid, as Joe the Squirrel's answer works - as of 2016.Cyano
there is a concern with the JavaScript solutions proposed. in the latest Chrome for example, HTML5 validation (required, etc.) is skipped. one solution i can think of is having two submit buttons, one hidden. a click should be triggered on the hidden button. the form should not be submitted without proper validation.Piscatelli
right after this comment, i discovered form.checkValidity() and form.reportValidity() which are not supported in Edge : )Piscatelli
thanks! now i can have a submit button outside form in modalsFarrington
B
54
<form method="get" id="form1" action="something.php">

</form>

<!-- External button-->
<button type="submit" form="form1">Click me!</button>

This worked for me, to have a remote submit button for a form.

Baylor answered 3/7, 2015 at 20:25 Comment(2)
thanks man, for this simple feature I don't want to write lines of JS code. PS: my app need not to support IEEuhemerize
Please vote here if you want to see the form attribute feature in MS Edge: wpdev.uservoice.com/forums/257854-microsoft-edge-developer/…Caffey
C
48

if you can use jQuery you can use this

<form method="get" action="something.php" id="myForm">
    <input type="text" name="name" />

    <input type="submit" style="display:none" />
</form>

<input type="button" value="Submit" id="myButton" />

<script type="text/javascript">
    $(document).ready(function() {
       $("#myButton").click(function() {
           $("#myForm").submit();
       });
    });
</script>

So, the bottom line is to create a button like Submit, and put the real submit button in the form(of course hiding it), and submit form by jquery via clicking the 'Fake Submit' button. Hope it helps.

Clairvoyant answered 1/2, 2013 at 22:26 Comment(1)
To make it work on both HTML5 ready browser and IE, here is my jQuery $('button[form]').click(function (){ var formId = $(this).attr('form'); $('#' + formId).submit(); });Evadnee
B
35

Similar to another solution here, with minor modification:

<form method="METHOD" id="FORMID">
   <!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>

https://www.w3schools.com/tags/att_form.asp

Busch answered 28/6, 2018 at 20:46 Comment(3)
This is the best answer, IMO. Straight from MDN on the button's form attribute: The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a <form> element in the same document. If this attribute is not specified, the <button> element will be associated to an ancestor <form> element, if one exists. This attribute enables you to associate <button> elements to <form> elements anywhere within a document, not just as descendants of <form> elements.Kaykaya
Be aware: That doesn't work in Internet Explorer 11. Try it here: cdpn.io/mdix/debug/PooPqaM/PNAvYKNJojRrTerrieterrier
WIth IE having been deprecated by Microsoft, we don't need to worry about "it doesn't work in IE" any more. Ever. Hooray! Thanks, Microsoft :) And thanks Google, too, for open-sourcing Chromium, so that Microsoft could base Edge on it.Soccer
G
26

You can tell a form that an external component from outside the <form> tag belongs to it by adding the form="yourFormId" to the definition of the component.

In this case,

<form id="login-form">
... blah...
</form>

<button type="submit" form="login-form" name="login_user" class="login-form-btn">
        <B>Log In</B>
</button>

... would still submit the form happily because you assigned the form name to it. The form thinks the button is part of it, even if the button is outside the tag, and this requires NO javascript to submit the form (which can be buggy i.e. form may submit but bootstrap errors / validations my fail to show, I tested).

Graehl answered 31/12, 2020 at 3:59 Comment(5)
for now, this should be the valid answerNola
The problem with this is that the default event won't have the form values in it.Joshia
Works with <input type="submit"> as a button too.Nitid
Fornewbies like I, please don't forget to add type="submit"Manna
@Greko2015GuFn it's already on the <button type="submit" declaration.Graehl
R
19

Try this:

<input type="submit" onclick="document.forms[0].submit();" />

Although I would suggest adding an id to the form and accessing by that instead of document.forms[index].

Rump answered 11/8, 2011 at 4:0 Comment(3)
Yeah I know how to do it with javascript, if you look I didn't tag it as javascript.Tusker
I'm sorry, wasn't clear from your post that you're looking for non JS way (I thought you missed tagging it under JS).Rump
This is the best way to do it if you want to submit an external form using a button inside another form.Banneret
K
12

You can always use jQuery:

<form id="myForm">
  <!-- form controls -->
</form>
<input type="submit" id="myButton">

<script>
$(document).ready(function () {
  $("#myButton").click(function () {
    $("#myForm").submit();
  });
});
</script>
Kusin answered 18/9, 2016 at 7:23 Comment(0)
R
10

Here's a pretty solid solution that incorporates the best ideas so far as well as includes my solution to a problem highlighted with Offerein's. No javascript is used.

If you care about backwards compatibility with IE (and even Edge 13), you can't use the form="your-form" attribute.

Use a standard submit input with display none and add a label for it outside the form:

<form id="your-form">
  <input type="submit" id="your-form-submit" style="display: none;">
</form>

Note the use of display: none;. This is intentional. Using bootstrap's .hidden class conflicts with jQuery's .show() and .hide(), and has since been deprecated in Bootstrap 4.

Now simply add a label for your submit, (styled for bootstrap):

<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
  Submit
</label>

Unlike other solutions, I'm also using tabindex - set to 0 - which means that we are now compatible with keyboard tabbing. Adding the role="button" attribute gives it the CSS style cursor: pointer. Et voila. (See this fiddle).

Revegetate answered 24/6, 2016 at 14:59 Comment(6)
Nice! Worked great with IE11 and firefox. Thanks!Hereditable
@Hereditable glad to hear it:)Revegetate
It's very helpful for you to put together all the features/suggestions from elsewhere, so thank you. However, even though you can now tab to the button/label, I can't see any way of "clicking" it from the keyboard, e.g. pressing Enter has no effect. Thus, being able to tab to it seems a little pointless. Is there a way to do this without using JavaScript?Catnip
@AndrewWillems that's a good point. Unfortunately I don't see a way around using your keyboard to trigger a click event without javascript. PS: if the post was helpful to you please upvote. It doesn't cost you anything but it means a lot to anyone who produces helpful answers.Revegetate
And I also love you for fixing the sloppy and invalid <input... /> self-closing syntax, which just about everybody's blatantly and incorrectly using here (too), to the proper void no-close tag! :) Kudos!Leisha
Oops, it seems to have changed in the meantime: the self-closing syntax for voids is now valid for HTML5.2.Leisha
T
7

Your <button> will need to have these 2 attributes: type="submit" and form="form_id" if it is outside a form. Example:

<form id="my-form">
   ...
</form>

<button type="submit" form="my-form">
   Submit
</button>

In addition, the <button> element can also have formmethod and formaction attributes that overrides the form's method and action respectively. Example:

<button type="submit" form="my-form" formmethod="post" formaction="/something.php">
   Submit
</button>

Here is the reference to all available attributes for the <button> element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button

Trapper answered 3/3, 2021 at 16:52 Comment(1)
Kudos for showing that nowadays you can have a self-submitting button, not requiring to be a 'member' of a form any more!Soccer
L
3

This work perfectly! ;)

This can be done using Ajax and with what I call: "a form mirror element". Instead to send a form with an element outside, you can create a fake form. The previous form is not needed.

<!-- This will do the trick -->
<div >
    <input id="mirror_element" type="text" name="your_input_name">
    <input type="button" value="Send Form">
</div>

Code ajax would be like:

    <script>
        ajax_form_mirror("#mirror_element", "your_file.php", "#your_element_response", "POST");

        function ajax_form_mirror(form, file, element, method) {
            $(document).ready(function() {
                // Ajax
                $(form).change(function() { // catch the forms submit event
                    $.ajax({                // create an AJAX call...
                        data: $(this).serialize(),      // get the form data
                        type: method,                   // GET or POST
                        url: file,                      // the file to call
                        success: function (response) {   // on success..
                        $(element).html(response);  // update the DIV
                        }
                    });

                    return false; // cancel original event to prevent form submitting
                });
            });
        }
   </script>

This is very usefull if you want to send some data inside another form without submit the parent form.

This code probably can be adapted/optimized according to the need. It works perfectly!! ;) Also works if you want a select option box like this:

<div>
    <select id="mirror_element" name="your_input_name">
        <option id="1" value="1">A</option>
        <option id="2" value="2">B</option>
        <option id="3" value="3">C</option>
        <option id="4" value="4">D</option>
    </select>
</div>

I hope it helped someone like it helped me. ;)

Lamee answered 28/7, 2016 at 10:46 Comment(0)
P
1

I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.

        <module-body>
            <form id="testform" method="post">
                <label>Input Title</label>
                <input name="named1" placeholder="Placeholder"  title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>
            </form>
        </module-body>
        <module-footer>
            <input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
            <input type="button" value="Reset">
        </module-footer>
Pals answered 6/10, 2019 at 18:41 Comment(0)
S
0

Maybe this could work, but I don't know if this is valid HTML.

<form method="get" action="something.php">
    <input type="text" name="name" />
    <input id="submitButton" type="submit" class="hide-submit" />
</form>

<label for="submitButton">Submit</label>
Swoosh answered 11/3, 2016 at 22:5 Comment(1)
This answer already exists for this very question itself. https://mcmap.net/q/73904/-submit-form-using-a-button-outside-the-lt-form-gt-tagSulph
V
0

I had an issue where I was trying to hide the form from a table cell element, but still show the forms submit-button. The problem was that the form element was still taking up an extra blank space, making the format of my table cell look weird. The display:none and visibility:hidden attributes didn't work because it would hide the submit button as well, since it was contained within the form I was trying to hide. The simple answer was to set the forms height to barely nothing using CSS

So,

CSS -

    #formID {height:4px;}

worked for me.

Vaden answered 14/9, 2019 at 16:31 Comment(1)
I may not be exactly an expert here, but how exactly does this answer the OP's question?Soccer

© 2022 - 2024 — McMap. All rights reserved.