Tim Lovell-Smith
Tim Lovell-Smith

Reputation: 16125

Can you have a single logical <form> split across multiple <div>s?

In my existing web page layout, which involves multiple files, one specifying the high-level layout, there are two elements, one for a left column, and one for a right column.

I want to have a single logical <form> (with a single action) where <input> elements are spread across both the left column and the right column. Is the only way to do this have the element be parent to both <div>s (and refactor my layout code), or is it possible to do something like <form [something]> inside both divs, so that clicking submit in one form submits all the inputs from both forms?

Upvotes: 17

Views: 21993

Answers (4)

Tim Lovell-Smith
Tim Lovell-Smith

Reputation: 16125

(Sorry to unaccept an answer and post my own, but I just found out apparently the answers I got are not up to date with HTML5!)

HTML5 introduces a form= attribute for <input> element [1]. So that you can do <input form="form1" name="input1" /> and have it in a nested inner form, or even outside of the` element.

[1] http://www.w3.org/TR/html5/association-of-controls-and-forms.html#attr-fae-form

Upvotes: 10

joequincy
joequincy

Reputation: 1395

I think people are missing the question. A <form> can contain whatever elements it needs. If the layout of your page is something like:

<body>
    <div id="leftColumn"><input name="foo" type="text"></div>
    <div id="rightColumn"><input name="bar" type="text"></div>
<body>

You don't need separate foo and bar forms. You can happily encase both of those <div>s inside a single <form> element:

<body>
    <form name="onlyOneForm">
        <div id="leftColumn"><input name="foo" type="text"></div>
        <div id="rightColumn"><input name="bar" type="text"></div>
    </form>
<body>

Upvotes: 10

Mr. Alien
Mr. Alien

Reputation: 157314

Short answer is No, you cannot have two separate form tags acting as a 1 form, instead wrap the whole thing inside a wrapping div tag

<form>
  <!-- some content with input elements has no relation with other form tag on this page, it just ends where you specify the end tag -->
</form>

<form>
  <!-- Has  no relation with the first form -->
</form>

Upvotes: 1

John Conde
John Conde

Reputation: 219804

The only way to submit both forms is to wrap both <div>s within a single <form> tag. Or, you can use jQuery/JavaScript to aggregate the data and submit them together as one submission.

Upvotes: 8

Related Questions