Html form inside other form

Is it valid to have a html form inside another html form?

In the official W3C XHTML specification, Section B. «Element Prohibitions», states that:

«form must not contain other form elements.»

As for the older HTML 3.2 spec, the section on the FORMS element states that:

«Every form must be enclosed within a FORM element. There can be several forms in a single document, but the FORM element can’t be nested.»

B. The Workaround

There are workarounds using JavaScript without needing to nest form tags.

«How to create a nested form.» (despite title this is not nested form tags, but a JavaScript workaround).

Answers to this StackOverflow question

Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it’s still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it’s not standard)

HTML 4.x & HTML5 disallow nested forms, but HTML5 allows a workaround with the «form» attribute («form owner»).

  1. Use an extra form(s) with only hidden fields & JavaScript to set its input’s and submit the form.
  2. Use CSS to line up several HTML form to look like a single entity — but it might be complicated to do.

In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.

The server side could look something like this if you use php:

As others have said, it is not valid HTML.

It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.

Источник

Is it valid to have a html form inside another html form?

In the official W3C XHTML specification, Section B. «Element Prohibitions», states that:

«form must not contain other form elements.»

As for the older HTML 3.2 spec, the section on the FORMS element states that:

«Every form must be enclosed within a FORM element. There can be several forms in a single document, but the FORM element can’t be nested.»

B. The Workaround

There are workarounds using JavaScript without needing to nest form tags.

«How to create a nested form.» (despite title this is not nested form tags, but a JavaScript workaround).

Читайте также:  Kotlin jackson data class

Note: Although one can trick the W3C Validators to pass a page by manipulating the DOM via scripting, it’s still not legal HTML. The problem with using such approaches is that the behavior of your code is now not guaranteed across browsers. (since it’s not standard)

Solution 2

In case someone find this post here is a great solution without the need of JS. Use two submit buttons with different name attributes check in your server language which submit button was pressed cause only one of them will be sent to the server.

The server side could look something like this if you use php:

Solution 3

HTML 4.x & HTML5 disallow nested forms, but HTML5 will allow a workaround with «form» attribute («form owner»).

  1. Use an extra form(s) with only hidden fields & JavaScript to set its input’s and submit the form.
  2. Use CSS to line up several HTML form to look like a single entity — but I think that’s too hard.

Solution 4

As others have said, it is not valid HTML.

It sounds like your are doing this to position the forms visually within each other. If that is the case, just do two separate forms and use CSS to position them.

Solution 5

No, the HTML specification states that no FORM element should contain another FORM element.

Источник

HTML Nested Form

In this article, we will see if can we create a nested form in HTML. Creating multiple forms within a form using tag is called a nested form. But we can’t create nested forms. Even if we create a nested form, it will automatically create separately. Let’s see an example:

html nested form

In this example code, we have created a form and inside it another form. Outside the form, we have gotten a “Name” input and created a “Submit” button. Inside the inner form, we have gotten “Email”, and “Password” and created a “Submit” button.

html nested form

See the above output, outer and inner form is successfully displayed. But see the element’s output below:

The child form is automatically merged with the parent form. Understand that, even if we create a nested form it will be merged, So we can create forms separately like:

Here, we have created two forms separately. This also gives us the same output. So, if you want to create a group form together, you need to use the or tags.

In summary, although it is possible to create a nested form in HTML, it may cause browser compatibility issues and is not recommended as it violates the HTML specification. It’s best to use other HTML elements to group related form elements together

Источник

Как отправить из html формы только часть данных

Бывает ситуация, когда нужно отправить форму с данными, которая уже вложена в другую форму. Обычно потребности могут быть при написании админской части web-приложения. Но вложенные формы стандартом HTML не допускаются. Вложенная форма при этом не работает. Предлагаем два метода решения данной проблемы.

Читайте также:  Clearing a stringbuilder java

Первый способ

В этом случае обработка и сортировка поступившей информации ложится целиком на сторону сервера. Сначала определяем какая из кнопок была нажата, затем на основании этой информации из всех данных выбираются нужные. Данный метод универсален с точки зрения работы в любой среде, работает во всех случаях, даже если у пользователя в браузере отключены скрипты. Недостаток способа в том, что передаются все поля из формы, а не только нужные.

Второй способ

Этот способ заключается в том, что из формы берутся нужные поля, затем динамически формируется новая форма и отправляется на сервер. Для этого придется сделать несколько вспомогательных действий. Разметка страницы может разная, мы укажем такую:

  //-------------------------------------------------------------------- // Создать временную форму и перенести в нее все элементы //-------------------------------------------------------------------- function ds(f) < var e=document.getElementById(f); if (!e) return false; // Создать временную форму var tmp_form = document.createElement("form"); tmp_form.method='get'; tmp_form.action='process.php'; // Адрес скрипта-обработчика формы tmp_form.style.display='none'; document.getElementsByTagName('body')[0].appendChild(tmp_form); // Перенести в нее все элементы cf(e,tmp_form); // Отправить созданную форму tmp_form.submit(); >//-------------------------------------------------------------------- // Перенести значения полей в форму //-------------------------------------------------------------------- function cf(e,f) < for (var i=0; i// Флажок checkbox case 'checkbox': < if (el.checked) < var tmp_el = document.createElement("input"); tmp_el.name=el.name; tmp_el.type='checkbox'; tmp_el.value=el.value; f.appendChild(tmp_el); tmp_el.checked=true; >break; > // Флажок radio case 'radio': < if (el.checked) < var tmp_el = document.createElement("input"); tmp_el.name=el.name; tmp_el.type='radio'; tmp_el.value=el.value; f.appendChild(tmp_el); tmp_el.checked=true; >break; > // Текстовое поле case 'hidden': < var tmp_el = document.createElement("input"); tmp_el.name=el.name; tmp_el.type='hidden'; tmp_el.value=el.value; f.appendChild(tmp_el); break; >// Поле ввода пароля case 'password': < var tmp_el = document.createElement("input"); tmp_el.name=el.name; tmp_el.type='hidden'; tmp_el.value=el.value; f.appendChild(tmp_el); break; >// Любые другие input'ы default: < break; >> > // Обработка textarea else if (elName=='textarea' && el.name!='') < var tmp_el = document.createElement("textarea"); tmp_el.name=el.name; tmp_el.value=el.value; f.appendChild(tmp_el); >// Обработка select else if (elName=='select' && el.name!='') < var tmp_el = document.createElement("input"); tmp_el.name=el.name; tmp_el.type='hidden'; tmp_el.value=el.value; f.appendChild(tmp_el); >else < // Обработать вложенный тег (рекурсия) cf(el,f); >> > 

© 2008 — 2022, ELsof.ru. Создание и поддержка сайтов. Раскрутка сайтов. Разработка Android приложений. Php скрипты

Источник

Допустимо ли иметь html-форму внутри другой html-формы?

Поэтому, когда вы отправляете «b», вы получаете только поля внутри внутренней формы. Когда вы отправляете «a», вы получаете все поля за вычетом значений «b».

Если это невозможно, какие обходные пути для этой ситуации доступны?

ОТВЕТЫ

Ответ 1

A. Это недопустимый HTML или XHTML

В официальной спецификации W3C XHTML, раздел B. «Запрещение элементов», говорится, что:

"form must not contain other form elements." 

Что касается более старой спецификации HTML 3.2, раздел элемента FORMS гласит:

«Каждая форма должна быть заключена в Элемент ФОРМА. Там может быть несколько формы в одном документе, но Элемент FORM не может быть вложенным. «

Б. Обходной путь

Есть обходные пути, использующие JavaScript без необходимости вложения тегов форм.

«Как создать вложенную форму.» (несмотря на заголовок, это не вложенные теги формы, а обходной путь JavaScript).

Примечание: Несмотря на то, что можно проверять валидаторы W3C, чтобы они пропускали страницу, манипулируя DOM с помощью сценариев, это все же не является допустимым HTML. Проблема с использованием таких подходов заключается в том, что поведение вашего кода теперь не гарантируется во всех браузерах. (так как это не стандарт)

Читайте также:  Default data types in javascript

Ответ 2

В случае, если кто-то найдет этот пост, это отличное решение без необходимости JS. Используйте две кнопки отправки с разными атрибутами имени, проверьте на своем сервере язык, на который была нажата кнопка отправки, потому что на сервер будет отправлено только одно из них.

Серверная сторона может выглядеть примерно так, если вы используете php:

Ответ 3

HTML 4.x и HTML5 запрещают вложенные формы, но HTML5 разрешает обходной путь с атрибутом «form» ( «владелец формы» ).

Что касается HTML 4.x, вы можете:

  • Используйте дополнительную форму с только скрытыми полями и JavaScript для установки ее ввода и отправки формы.
  • Используйте CSS для выстраивания нескольких HTML-форм, чтобы они выглядели как единое целое, но я думаю, что это слишком сложно.

Ответ 4

Как говорили другие, это недействительно HTML.

Похоже, что вы делаете это, чтобы визуально визуализировать формы друг в друге. Если это так, просто выполните две отдельные формы и используйте CSS для их размещения.

Ответ 5

Нет, спецификация HTML указывает, что элемент FORM не должен содержать другого элемента FORM .

Ответ 6

скорее используйте собственный javascript-метод внутри атрибута действия формы!

   var input1 = null; var input2 = null; function InitInputs() < if (input1 == null) < input1 = document.getElementById("input1"); >if (input2 == null) < input2 = document.getElementById("input2"); >if (input1 == null) < alert("input1 missing"); >if (input2 == null) < alert("input2 missing"); >> function myMethod1() < InitInputs(); alert(input1.value + " " + input2.value); >function myMethod2()  

Ответ 7

Вы можете легко ответить на свой вопрос, введя HTML-код в W3 Validator. (В нем есть поле для ввода текста, вам даже не придется размещать свой код на сервере. )

(И нет, это не будет подтверждено.)

Ответ 8

Возможность иметь iframe внутри внешней формы. В iframe содержится внутренняя форма. Обязательно используйте тег внутри тега заголовка iframe, чтобы форма выглядела как часть главной страницы.

Ответ 9

Ответ 10

Нет, это неверно. Но «решение» может создавать модальное окно вне формы «a», содержащее форму «b».

Это можно легко сделать, если вы используете bootstrap или материализуете css. Я делаю это, чтобы избежать использования iframe.

Ответ 11

Если вам нужна ваша форма для отправки/фиксации данных в реляционную базу данных 1: M, я бы рекомендовал создать триггер «после вставки» в таблице A, который вставляет необходимые данные для таблицы B.

Ответ 12

Нет, это недопустимо, но вы можете изменить свою внутреннюю позицию на HTML с помощью CSS и jQuery . Сначала создайте некоторый контейнерный div внутри вашей родительской формы, а затем в любом другом месте на странице div с вашей дочерней (внутренней) формой:

  

Ответ 13

Даже если это разрешено (а это не так), он создает очень запутанный пользовательский интерфейс.

Для пользователя форма представляет собой форму, и вы не должны изменять ее, если вы не хотите добавить путаницу.

Источник

Оцените статью