Формы в HTML. Несколько кнопок отправки в HTML-форме
Attribute contains a DOMString which is displayed as the button"s label. Buttons do not have a true value otherwise.
If you don"t specify a value , the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here"s an example of a submit button with a default label in your browser:
Additional attributes
formenctype
A string that identifies the encoding method to use when submitting the form data to the server. There are three permitted values:
Application/x-www-form-urlencoded This, the default value, sends the form data as a string after URL encoding the text using an algorithm such as . multipart/form-data Uses the FormData API to manage the data, allowing for files to be submitted to the server. You must use this encoding type if your form includes any element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> elements of type file (). text/plain Plain text; mostly useful only for debugging, so you can easily see the data that"s to be submitted.
If specified, the value of the formenctype attribute overrides the owning form"s action attribute.
formmethod
A string indicating the HTTP method to use when submitting the form"s data; this value overrides any method attribute given on the owning form. Permitted values are:
Get A URL is constructed by starting with the URL given by the formaction or action attribute, appending a question mark ("?") character, then appending the form"s data, encoded as described by formenctype or the form"s enctype attribute. This URL is then sent to the server using an HTTP request. This method works well for simple forms that contain only ASCII characters and have no side effects. This is the default value. post The form"s data is included in the body of the request that is sent to the URL given by the formaction or action attribute using an HTTP post request. This method supports complex data and file attachments. dialog This method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all.
formnovalidate
A Boolean attribute which, if present, specifies that the form should not be validated before submission to the server. This overrides the value of the novalidate attribute on the element"s owning form.
formtarget
A string which specifies a name or keyword that indicates where to display the response received after submitting the form. The string must be the name of a browsing context (that is, a tab, window, or ) represents a nested browsing context, embedding another HTML page into the current one.">
In addition to the actual names of tabs, windows, or inline frames, there are a few special keywords that can be used:
Self Loads the response into the same browsing context as the one that contains the form. This will replace the current document with the received data. This is the default value used if none is specified. _blank Loads the response into a new, unnamed, browsing context. This is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent . _parent Loads the response into the parent browsing context of the current one. If there is no parent context, this behaves the same as _self . _top Loads the response into the top-level browsing context; this is the browsing context that is the topmost ancestor of the current context. If the current context is the topmost context, this behaves the same as _self .
Using submit buttons
buttons are used to submit forms. If you want to create a custom button and then customize the behavior using JavaScript, you need to use , or better still, a element.
If you choose to use
A simple submit button
We"ll begin by creating a form with a simple submit button:
This renders like so:
Try entering some text into the text field, and then submitting the form.
Upon submitting, the data name/value pair gets sent to the server. In this instance, the string will be text=usertext , where "usertext" is the text entered by the user, encoded to preserve special characters. Where and how the data is submitted depends on the configuration of the
For example, in Firefox for Mac, pressing Control - Option - S triggers the Send button, while Chrome on Windows uses Alt + S .
The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn"t interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it"s not a complete solution for accessibility purposes.
Disabling and enabling a submit button
To disable a submit button, simply specify the disabled global attribute on it, like so:
You can enable and disable buttons at run time by simply setting disabled to true or false ; in JavaScript this looks like btn.disabled = true or btn.disabled = false .
Validation
Submit buttons don"t participate in constraint validation; they have no real value to be constrained.
Examples
We"ve included simple examples above. There isn"t really anything more to say about submit buttons. There"s a reason this kind of control is sometimes called a "simple button."
Specifications
Specification | Status | Comments |
---|---|---|
HTML Living Standard The definition of "" in that specification. |
Living Standard | |
HTML5 The definition of "" in that specification. |
Recommendation |
Browser compatibility
The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | |
Basic support | Chrome Full support 1 | Edge Full support Yes | Firefox Full support 1 |
Зачастую на Web – сайтах можно встретить страницы с размещенными на них HTML - формами. Веб-формы – удобный способ получения информации от посетителей вашего сайта. Пример тому – , – которая обеспечивает обратную связь с посетителями и разработчиками сайта. Формы так же удобны и для разработчиков сайта при разработке CMS, которая позволяет поддерживать главное свойство сайта - актуальность. Данная статья посвящена основам создания HTML-форм, их обработке и способам передачи данных из экранных форм в PHP-сценарии.
1) Создание простой формы
Теги и задают начало и конец формы. Начинающий форму тег содержит два атрибута: action и method . Атрибут action содержит адрес URL сценария, который должен быть вызван для обработки сценария. Атрибут method указывает браузеру, какой вид HTTP запроса необходимо использовать для отправки формы; возможны значения POST и GET .
Замечание
Главное отличие методов POST и GET заключается в способе передачи информации. В методе GET параметры передаются через адресную строку, т.е. по сути в HTTP-заголовке запроса, в то время как в методе POST параметры передаются через тело HTTP-запроса и никак не отражаются на виде адресной строки.
В данной html-форме присутствует элемент browse , который открывает диалоговое окно для выбора файла для загрузки на сервер. При нажатии на кнопку "Передать файл" , файл передается сценарию-обработчику.
Затем необходимо написать сценарий обработчик action.php . Перед написание обработчика необходимо определиться в какой каталог мы будет копировать файл:
if(isset($_FILES
[
"myfile"
]))
// Если файл существует
{
$catalog
=
"../image/"
;
// Наш каталог
if (is_dir
($catalog
))
// Если такой каталог есть
{
$myfile
=
$_FILES
[
"myfile"
][
"tmp_name"
];
// Времменый файл
$myfile_name
=
$_FILES
[
"myfile"
][
"name"
];
// Имя файла
if(!
copy
($myfile
,
$catalog
)) echo
"Ошибка при копировании файла "
.
$myfile_name
// Если неудалось скопировать файл
}
else
mkdir
("../image/"
);
// Если такого каталога нет, то мы его создадим
}
?>
Замечание
Если вы доверяете пользователям закачивать на ваш сервер любые файлы, нужно быть предельно осторожным. Злоумышленники могут внедрить «нехороший» код в картинку или файл и отправить на сервер. В таких случаях нужно жестоко контролировать загрузку файлов.
Данный пример демонстрирует создание каталога и копирование файла в этот каталог на сервер.
Также хотел бы продемонстрировать пример с элементом checkbox . Этот элемент немного отличается от других элементов тем, что если не один из элементов checkbox ’a не выбран, то суперглобальная переменная $_POST вернет пустое значение:
if (!empty($_POST
[
"mycolor"
])) echo
$_POST
[
"mycolor"
];
// Если выбран хоть 1 элемент
else echo
"Выберите значение"
;
?>
С приходом HTML5 формы сталее более универсальными. Элемент input теперь может содержать электронные адреса, даты и много другое, их можно отмечать как обязательные не прибегая к javascript – и это всего лишь некоторые из наиболее ценных возможностей. Также теперь для одной формы можно задействовать несколько submit кнопок, а также теперь есть возможность вынести кнопку submit за пределы формы.
Несколько submit внутри одной формы
До недавнего времени в форму можно было вставить только одну кнопку submit, в противном случае форма обрабатывала только последнюю кнопку. Добавляя method="post" и url к элементу формы "form" мы получали рабочую форму.
Теперь ситуация изменилась – в HTML добавили новые свойства "formmethod" и "formaction". Они позволяют добавить метод post и url непосредственно в кнопку "submit", таким образом к form ничего дописывать не нужно. Имея эти параметры, прикрепленные к кнопке "submit", а не к form – все это добавляет больше гибкости форме. Теперь можно сделать столько кнопок, сколько будет необходимо для формы.
Теперь каждая кнопка "submit" относится к разным url и все это избавляет от того, что при верстке необходимо писать javascript код. Все это отлично работает и теперь по нажатии на какую-нибудь кнопку форма получит formmethod и formaction, которые перезапишут стандартные параметры method и action. Если в форме будет присутствовать обычная кнопка "submit" без новых параметров, то он вернет форме значения, установленные для элемента form.
Свойства formmethod и formaction поддерживаются всеми популярными браузерами
Элементы формы (input, select, textarea) за пределами формы
Общепринятый факт, что все элементы формы, принадлежащие ей должны находится внутри элемента
На сегодняшний день аттрибут form поддерживается всеми популярными браузерами, за исключением Internet Explorer (вплоть до 10й версии).
Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега
В этом примере данные формы, обозначенные атрибутом name (login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.
Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге