开发者

With nested HTML forms, is it possible to target which one's content is transmitted upon submit?

开发者 https://www.devze.com 2022-12-08 07:09 出处:网络
I have a form within another form: <form id=\"a\"> <form id=\"b\"> <input type=\"submit\">

I have a form within another form:

<form id="a">
    <form id="b">
        <input type="submit">

When the submit button is clicked, it seems that the outer form is submitted.

Is 开发者_运维问答there a way to target which form is submitted?


No, nested forms aren't supported:

There can be several forms in a single document, but the FORM element can't be nested.

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


The HTML DTD specifically forbids a form element from containing another form element:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

http://www.w3.org/TR/html401/interact/forms.html#edef-FORM


Like others have said...nested forms aren't allowed.

However, that doesn't mean some browsers won't do something with such. In the example that you have presented, the browser appears to be ignoring the second <form> tag in a similar fashion to how an unknown tag (i.e. <notAValidTag>) is also ignored. Since JavaScript also doesn't allow for embedded form collections, the best way to ensure that FormB's information is submitted is to make it no longer a nested form. This will break up your markup and UI into more distinct sections which may be beneficial from a UX perspective as well.


i think this is not allowed by the html standard.


In HTML 5, yes. Each input element can have a "form" attribute signalling which form it belongs to. However, it is still invalid to nest forms in HTML and HTML parsers won't allow this to happen.

However, it is possible to construct nested forms via JavaScript. In the absence of the form attribute, the rules for determining which form an input belongs to are quite complex, but they are described in full with an example at http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#association-of-controls-and-forms

Specifically, step 5 of Reset the Form Owner says:

Otherwise, if element has an ancestor form element, then associate element with the nearest such ancestor form element.

Clearly, "nearest" would not need to be said if form nesting was impossible.

Then step 4 explains how the required form can be targeted, by associating the submit button to the required form though the "form" attribute on the button.

If element is listed, has a form content attribute, and is connected, then:

If the first element in element's tree, in tree order, to have an ID that is identical to element's form content attribute's value, is a form element, then associate the element with that form element.

0

精彩评论

暂无评论...
验证码 换一张
取 消