493

Is it possible to nest html forms like this

<form name="mainForm">
  <form name="subForm">
  </form>
</form>

so that both forms work? My friend is having problems with this, a part of the subForm works, while another part of it does not.

Mark Garcia
  • 16,438
  • 3
  • 50
  • 93
Levi
  • 11,104
  • 13
  • 40
  • 47
  • He is setting up a cart, where the update quantity is inside of the form that keeps track of totals. I personally wouldn't do that, but he is running into problems getting that to work. – Levi Dec 18 '08 at 22:58
  • 1
    Seems like he'd be better off using Javascript to copy values from one form to the other, rather than trying to nest them. I don't think the nesting will work. – Ben Dec 18 '08 at 23:04
  • 15
    Old question, but to answer the comment, nesting forms could be necessary to avoid JavaScript. I'm coming across this because I'd like to nest forms for subform "reset" buttons, which don't require JavaScript to be enabled. – vol7ron Jun 15 '11 at 18:12
  • Yes, i had a problem same as you. And i use ajax submit form to solve this problem. – Khanh Pham Nov 13 '15 at 04:56
  • You would even have problems making it work in different versions of the same browser. So avoid using that. – MP. Oct 22 '09 at 18:02

20 Answers20

492

In a word, no. You can have several forms in a page but they should not be nested.

From the html5 working draft:

4.10.3 The form element

Content model:

Flow content, but with no form element descendants.

mb21
  • 28,026
  • 6
  • 96
  • 118
Craig
  • 34,658
  • 33
  • 108
  • 191
  • 2
    Chances are this is a .net app (which wraps a
    tag around everything). Any time you try to nest forms, there is a design flaw somewhere. Ususally you want two forms next to each other, wrapped in a single DIV for styling purposes only.
    – Ryan Wheale Oct 09 '12 at 22:59
  • 141
    I agree with the answer, but to ask another, why not? Why does HTML not allow for nesting forms? To me, it appears to be a limitation that we would be better off without. There are many examples where using nested forms would be easier to program (i.e. using an upload photo form with a profile edit form). – Ryan Apr 06 '13 at 01:32
  • 26
    @Nilzor he's not asking whether or not it can't be done, he's asking WHY not. I agree; nesting forms is actually really useful. So if you have a one page app with tabs, each tab is its own form (so you can submit it to save progress), and they're all wrapped in a form, which you can submit to save everything. Makes sense to me. – Rob Grant Dec 24 '13 at 06:45
  • 6
    I agree with what others have said. This limitation seems arbitrary and harmful. – aroth Jul 07 '14 at 06:43
  • 17
    So we need HTML 5.1 with nested forms. – Hector Jun 22 '16 at 10:33
  • 1
    There is no problem I believe with nesting forms if you are submitting those forms with AJAX. I believe the OP is talking about an actual postback, no? – Jordan Jan 04 '17 at 17:31
  • 6
    The problem with nested forms is the form architecture within HTML, where action within that form leads to a submit event. The question gets hair about what needs to be submitted. You may have several fields within a form, or several forms within a div, but it doesn't really make sense to have forms within a form. If content goes together, it's all one form; if content is submitted separately, it's really separate forms that don't need an outer form. – Kyle Baker Apr 10 '17 at 23:18
  • Could you explain to me what is flow? Thanks – Rafael Andrade Apr 18 '18 at 19:32
  • @RafaelAndrade Elements belonging to the flow content category typically contain text or embedded content. – Mark Baijens Sep 21 '18 at 09:12
  • Another difficulty is that in the DOM elements have a form property which is the form they belong to. So you can't have elements belonging to more than one form which they would in the nested form. – Rudiger W. Jan 16 '19 at 12:11
  • @aroth why do you say harmful? – Surya Pratap Nov 24 '19 at 05:03
  • Because it puts an arbitrary restriction on how the markup language can be used. In a markup language that is seldom syntax-checked or validated and where different browsers tend to accommodate different levels of incorrect/non-standard syntax anyways. And rules out certain structures that could be beneficial in certain edge cases (some examples of which are noted in other comments, above). It seems both more sensible and more _useful_ for nested `form` elements to be allowed. – aroth Nov 24 '19 at 15:51
  • Whilst this answers the question directly. There's a better way. See @Creative's answer using the form attribute on input elements. – Mark May 06 '20 at 11:35
127

I ran into a similar problem, and I know that is not an answer to the question, but it can be of help to someone with this kind of problem:
if there is need to put the elements of two or more forms in a given sequence, the HTML5 <input> form attribute can be the solution.

From http://www.w3schools.com/tags/att_input_form.asp:

  1. The form attribute is new in HTML5.
  2. Specifies which <form> element an <input> element belongs to. The value of this attribute must be the id attribute of a <form> element in the same document.

Scenario:

  • input_Form1_n1
  • input_Form2_n1
  • input_Form1_n2
  • input_Form2_n2

Implementation:

<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>

<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />

<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />

Here you'll find browser's compatibility.

Cliff Burton
  • 2,529
  • 20
  • 30
  • 39
  • 2
    Just to point the browser-support table: https://caniuse.com/#feat=form-attribute Resuming - it works everywhere(Chrome, Firefox, Opera, Egde, Safari, Android browser...) except IE (including latest by now v11). – dmikam Jul 27 '18 at 10:57
  • @cliff-burton, what is the difference here? I just can see inputs outside of the form. It still would need JS to submit both forms at the same time. Wouldn't it? – sdlins Apr 29 '20 at 21:42
  • Uh, it's been a long time since the last time I used this but I think JS is not required for submitting the form. Provided that the `` that specifies an `action`, the ``(s) linked to that same `
    ` will be used in that request
    – Cliff Burton Apr 30 '20 at 13:45
92

The second form will be ignored, see the snippet from WebKit for example:

bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
    // Only create a new form if we're not already inside one.
    // This is consistent with other browsers' behavior.
    if (!m_currentFormElement) {
        m_currentFormElement = new HTMLFormElement(formTag, m_document);
        result = m_currentFormElement;
        pCloserCreateErrorCheck(t, result);
    }
    return false;
}
Vitalii Fedorenko
  • 97,155
  • 26
  • 144
  • 111
55

It is possible to achieve the same result as nested forms, but without nesting them.

HTML5 introduced the form attribute. You can add the form attribute to form controls outside of a form to link them to a specific form element (by id).

https://www.impressivewebs.com/html5-form-attribute/

This way you can structure your html like this:

<form id="main-form" action="/main-action" method="post"></form>
<form id="sub-form"  action="/sub-action"  method="post"></form>

<div class="main-component">
    <input type="text" name="main-property1" form="main-form" />
    <input type="text" name="main-property2" form="main-form" />

    <div class="sub-component">
        <input type="text" name="sub-property1" form="sub-form" />
        <input type="text" name="sub-property2" form="sub-form" />
        <input type="submit" name="sub-save" value="Save" form="sub-form" />
    </div>

    <input type="submit" name="main-save" value="Save" form="main-form" />
</div>

The form attribute is supported by all modern browsers. IE does not support this though but IE is not a browser anymore, rather a compatibility tool, as confirmed by Microsoft itself: https://www.zdnet.com/article/microsoft-security-chief-ie-is-not-a-browser-so-stop-using-it-as-your-default/. It's about time we stop caring about making things work in IE.

https://caniuse.com/#feat=form-attribute
https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form

From the html spec:

This feature allows authors to work around the lack of support for nested form elements.

Creative
  • 664
  • 5
  • 7
  • what is the difference here? I just can see inputs outside of the form. It still would need JS to submit both forms at the same time. Wouldn't it? – sdlins Apr 29 '20 at 21:43
  • 1
    @sdlins No, the idea is to style main-component and sub-component as how you want them to look, nested. The actual 2 form tags will be invisible. Each submit button will trigger it's respective form submit. No javascript is required. – Creative May 04 '20 at 12:54
  • if you want trigger only one *or* other form, ok. But how would it resolve when you need trigger the "parent" form *with* its child forms as it was one and without js? – sdlins May 04 '20 at 16:25
  • 1
    @sdlins that's not what this question is about. The question is about 2 different forms, but have them nested. I'm wondering why you want to have 2 forms but still 1 submit function? Can't you just have 1 form then? You'll indeed have to resort to javascript for something as weird as that :P – Creative May 05 '20 at 16:42
  • yeah, you're right, that isn't the OP question. I will post my own. Thank you! – sdlins May 05 '20 at 20:06
44

Plain html cannot allow you to do this. But with javascript you can be able to do that. If you are using javascript/jquery you could classify your form elements with a class and then use serialize() to serialize only those form elements for the subset of the items you want to submit.

<form id="formid">
    <input type="text" class="class1" />
    <input type="text" class="class2">
</form>

Then in your javascript you could do this to serialize class1 elements

$(".class1").serialize();

For class2 you could do

$(".class2").serialize();

For the whole form

$("#formid").serialize();

or simply

$("#formid").submit();
HSchmale
  • 1,541
  • 2
  • 17
  • 40
Solomon Kariri
  • 567
  • 4
  • 4
32

If you're using AngularJS, any <form> tags inside your ng-app are replaced at runtime with ngForm directives that are designed to be nested.

In Angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of <form> elements, so Angular provides the ngForm directive which behaves identically to <form> but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. (source)

roufamatic
  • 17,295
  • 7
  • 53
  • 84
12

Another way to get around this problem, if you are using some server side scripting language that allows you to manipulate the posted data, is to declare your html form like this :

<form>
<input name="a_name"/>
<input name="a_second_name"/>
<input name="subform[another_name]"/>
<input name="subform[another_second_name]"/>
</form>

If you print the posted data (I will use PHP here), you will get an array like this :

//print_r($_POST) will output :
    array(
    'a_name' => 'a_name_value',
    'a_second_name' => 'a_second_name_value',
    'subform' => array(
      'another_name' => 'a_name_value',
      'another_second_name' => 'another_second_name_value',
      ),
    );

Then you can just do something like :

$my_sub_form_data = $_POST['subform'];
unset($_POST['subform']);

Your $_POST now has only your "main form" data, and your subform data is stored in another variable you can manipulate at will.

Hope this helps!

Pierre
  • 4,607
  • 12
  • 48
  • 71
12

As Craig said, no.

But, regarding your comment as to why:

It might be easier to use 1 <form> with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>.

Jonathan Lonowski
  • 112,514
  • 31
  • 189
  • 193
  • I made my cart page like that, he just went a different way and didn't want to change it. I wasn't positive if his method was all that valid either. – Levi Dec 18 '08 at 23:05
9

Note you are not allowed to nest FORM elements!

http://www.w3.org/MarkUp/html3/forms.html

https://www.w3.org/TR/html4/appendix/changes.html#h-A.3.9 (html4 specification notes no changes regarding nesting forms from 3.2 to 4)

https://www.w3.org/TR/html4/appendix/changes.html#h-A.1.1.12 (html4 specification notes no changes regarding nesting forms from 4.0 to 4.1)

https://www.w3.org/TR/html5-diff/ (html5 specification notes no changes regarding nesting forms from 4 to 5)

https://www.w3.org/TR/html5/forms.html#association-of-controls-and-forms comments to "This feature allows authors to work around the lack of support for nested form elements.", but does not cite where this is specified, I think they are assuming that we should assume that it's specified in the html3 specification :)

Mark Peterson
  • 570
  • 5
  • 17
  • 23
    I have no idea why you'd post on a question that has been answered 3 and a half years, but more problematic is linking to HTML3 which hasn't been a recommendation for a long time. – Aidiakapi Dec 24 '13 at 13:16
  • 7
    It's a reference to how long the underlying question has been answered, which I believed to be constructive. Also I found the tact-free "Note you are not allowed to nest FORM elements!" within the spec to be humorous. – Mark Peterson Feb 13 '14 at 20:03
  • 1
    This is a problem because I have to insert an API that is a form and because .net app (which wraps a
    tag around everything). How do you overcome this issue.
    – jelly46 Mar 27 '14 at 16:53
5

You can also use formaction="" inside the button tag.

<button type="submit" formaction="/rmDog" method='post' id="rmDog">-</button>

This would be nested in the original form as a separate button.

Chief Buddy
  • 61
  • 1
  • 3
  • this doesn't answer the question but this just helped me solve another problem I was having so giving upvote – codeAndStuff Nov 06 '18 at 15:10
  • ignore above (wouldn't let me edit after 5 minutes...hmm). huge help here - exactly mapped onto what I was attempting to do this morning. this is why we all love SO – codeAndStuff Nov 06 '18 at 15:16
4

A simple workaround is to use a iframe to hold the "nested" form. Visually the form is nested but on the code side its in a separate html file altogether.

Ezion
  • 49
  • 2
4

Use empty form tag before your nested form

Tested and Worked on Firefox, Chrome

Not Tested on I.E.

<form name="mainForm" action="mainAction">
  <form></form>
  <form name="subForm"  action="subAction">
  </form>
</form>

EDIT by @adusza: As the commenters pointed out, the above code does not result in nested forms. However, if you add div elements like below, you will have subForm inside mainForm, and the first blank form will be removed.

<form name="mainForm" action="mainAction">
  <div>
      <form></form>
      <form name="subForm"  action="subAction">
      </form>
  </div>
</form>
Andrea Dusza
  • 1,940
  • 3
  • 15
  • 27
Fatih
  • 518
  • 8
  • 17
  • 1
    when i tried this on chrome it outputs this
    – ianace Sep 10 '15 at 22:11
  • 1
    Did you tried with submit button. I'm used this method many times and always worked. – Fatih Sep 30 '15 at 08:04
  • 13
    This is a violation of the specification and using it is begging for future problems. – Oskar Berggren Jan 28 '16 at 14:45
  • Newer webkit versions just remove the nested form elements. – woens Aug 03 '18 at 09:49
  • 1
    This only seems to work when the `innerHTML` of `mainForm` is set via JavaScript (i.e. ajax). Just having this snippet in an HTML file will not result in nested forms: the empty form tag will terminate the outer one, and `subForm` will be just after `mainForm` (tested on Chrome 86 and Firefox 80). Strangely, when setting `innerHTML`, only the first nested form is removed, and the rest are kept nested. – Tamas Hegedus Nov 13 '20 at 20:13
  • 1
    Update, you don't need ajax if there is another element, like a div between the outer and the inner forms. Weird. – Tamas Hegedus Nov 13 '20 at 21:14
3

While I don't present a solution to nested forms (it doesn't work reliably), I do present a workaround that works for me:

Usage scenario: A superform allowing to change N items at once. It has a "Submit All" button at the bottom. Each item wants to have its own nested form with a "Submit Item # N" button. But can't...

In this case, one can actually use a single form, and then have the name of the buttons be submit_1..submit_N and submitAll and handle it servers-side, by only looking at params ending in _1 if the name of the button was submit_1.

<form>
    <div id="item1">
        <input type="text" name="foo_1" value="23">
        <input type="submit" name="submit_1" value="Submit Item #1">
    </div>
    <div id="item2">
        <input type="text" name="foo_2" value="33">
        <input type="submit" name="submit_2" value="Submit Item #2">
    </div>
    <input type="submit" name="submitAll" value="Submit All Items">
</form>

Ok, so not much of an invention, but it does the job.

Peter V. Mørch
  • 9,433
  • 5
  • 46
  • 65
3

Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.

Mike Hofer
  • 14,871
  • 10
  • 63
  • 103
2

About nesting forms: I spent 10 years one afternoon trying to debug an ajax script.

my previous answer/example didn't account for the html markup, sorry.

<form id='form_1' et al>
  <input stuff>
  <submit onClick='ajaxFunction(That_Puts_form_2_In_The_ajaxContainer)' >
  <td id='ajaxContainer></td>
</form>

form_2 constantly failed saying invalid form_2.

When I moved the ajaxContainer that produced form_2 <i>outside</i> of form_1, I was back in business. It the answer the question as to why one might nest forms. I mean, really, what's the ID for if not to define which form is to be used? There must be a better, slicker work around.

Wh1T3h4Ck5
  • 8,045
  • 9
  • 52
  • 74
larry
  • 29
  • 1
2

Although the question is pretty old and I agree with the @everyone that nesting of form is not allowed in HTML

But this something all might want to see this

where you can hack(I'm calling it a hack since I'm sure this ain't legitimate) html to allow browser to have nested form

<form id="form_one" action="http://apple.com">
  <div>
    <div>
        <form id="form_two" action="/">
            <!-- DUMMY FORM TO ALLOW BROWSER TO ACCEPT NESTED FORM -->
      </form>
    </div>
      <br/>
    <div>
      <form id="form_three" action="http://www.linuxtopia.org/">
          <input type='submit' value='LINUX TOPIA'/>
      </form>
    </div>
      <br/>

    <div>
      <form id="form_four" action="http://bing.com">
          <input type='submit' value='BING'/>
      </form>
    </div>
      <br/>  
    <input type='submit' value='Apple'/>
  </div>  
</form>

JS FIDDLE LINK

http://jsfiddle.net/nzkEw/10/

Viren
  • 5,764
  • 6
  • 35
  • 91
1

No you cannot have a nested form. Instead you can open up a Modal that contains form and perform Ajax form submit.

1

Really not possible... I couldn't nest form tags... However I used this code:

<form>
    OTHER FORM STUFF

    <div novalidate role="form" method="post" id="fake_form_id_0" data-url="YOUR_POST_URL">
        THIS FORM STUFF
    </div>
</form>

with {% csrf_token %} and stuff

and applied some JS

var url = $(form_id).attr("data-url");

$.ajax({
  url: url,
  "type": "POST",
   "data": {
    'csrfmiddlewaretoken': '{{ csrf_token }}',
    'custom-param-attachment': 'value'
  },
  success: function (e, data) {
      if (e.is_valid) {
         DO STUFF
      }
  }
});
diogosimao
  • 133
  • 8
0

Today, I also got stuck in same issue, and resolve the issue I have added a user control and
on this control I use this code

<div class="divformTagEx">

</div>

<asp:Literal runat="server" ID="litFormTag" Visible="false">
'<div> <form  style="margin-bottom: 3;" action="http://login.php" method="post" name="testformtag"></form> </div>'</asp:Literal>

and on PreRenderComplete event of the page call this method

private void InitializeJavaScript()
{
        var script = new StringBuilder();
        script.Append("$(document).ready(function () {");
        script.Append("$('.divformTagEx').append( ");
        script.Append(litFormTag.Text);
        script.Append(" )");
        script.Append(" });");
        ScriptManager.RegisterStartupScript(this, GetType(), "nestedFormTagEx", script.ToString(), true);
    }

I believe this will help.

doppelgreener
  • 5,752
  • 8
  • 42
  • 59
0

Before I knew I wasn't supposed to do this I had nested forms for the purpose of having multiple submit buttons. Ran that way for 18 months, thousands of signup transactions, no one called us about any difficulties.

Nested forms gave me an ID to parse for the correct action to take. Didn't break 'til I tried to attach a field to one of the buttons and Validate complained. Wasn't a big deal to untangle it--I used an explicit stringify on the outer form so it didn't matter the submit and form didn't match. Yeah, yeah, should've taken the buttons from a submit to an onclick.

Point is there are circumstances where it's not entirely broken. But "not entirely broken" is perhaps too low a standard to shoot for :-)

Roger Krueger
  • 233
  • 2
  • 8