ChatGPT解决这个技术问题 Extra ChatGPT

Submit form using a button outside the <form> tag

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?

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?
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?
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.
@Kumar, I also thought it would be impossible, but it looks like it is not stackoverflow.com/a/23456905/932473

B
Black

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"/>

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.
Which IE versions exactly?
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 ofc
If you want to see the form attribute in MS Edge please vote here: wpdev.uservoice.com/forums/257854-microsoft-edge-developer/…
A vanilla-JS version of @AdrianFöder fallback would be: <button type="submit" form="frmFoo" onclick="!this.form && document.getElementById('myform').submit()">
O
Offereins

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.


better solution imho without require js and major changes :)
Works in IE 11 too. I know, you don't often see "works" and "IE" in the same sentence.
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.
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)
To focus the label via tab button, you can use tabindex HTML attribute: <label for="submit-form" tabindex="0">Submit</label> as per this question
J
Josef Engelfrost

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?


FYI, HTML5 support, not perfect yet but it's getting there: impressivewebs.com/html5-form-attribute
I am a bit late here, but how can you put the input in the form, but position it somewhere else?
You can use
The answer is no longer valid, as Joe the Squirrel's answer works - as of 2016.
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.
J
Joe the Squirrel
<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.


thanks man, for this simple feature I don't want to write lines of JS code. PS: my app need not to support IE
Please vote here if you want to see the form attribute feature in MS Edge: wpdev.uservoice.com/forums/257854-microsoft-edge-developer/…
b
brainjam

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.


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(); });
m
mster

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


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
element in the same document. If this attribute is not specified, the
Be aware: That doesn't work in Internet Explorer 11. Try it here: cdpn.io/mdix/debug/PooPqaM/PNAvYKNJojRr
G
GeoSn0w

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).


for now, this should be the valid answer
The problem with this is that the default event won't have the form values in it.
Works with as a button too.
Fornewbies like I, please don't forget to add type="submit"
@Greko2015GuFn it's already on the
M
Mrchief

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].


Yeah I know how to do it with javascript, if you look I didn't tag it as javascript.
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).
This is the best way to do it if you want to submit an external form using a button inside another form.
A
Aravind Suresh

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>

J
Jonathan

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).


Nice! Worked great with IE11 and firefox. Thanks!
@eaglei22 glad to hear it:)
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?
@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.
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!
m
maelga

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


T
Thanaen

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. ;)


E
Emmanuel Lozoya

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>

This answer already exists for this very question itself. stackoverflow.com/a/23456905/2968465
S
SotoArmando

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>

S
Shawn Game

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.