Атрибуты полей форм
Содержание:
Defining the Structure of a Form
Every web form must be wrapped in tags. In most cases, all of the form fields will be nested between these tags. There are several attributes that may optional be used with the element, including: : This optional attribute is used to identify the character encodings acceptable to the server and code processing form input. If more than one encoding is specified, one space should be placed between each encoding. If left blank or not provided, the encoding will default to the same encoding as the document containing the form. : This attribute is used to specify a URL where form data should be sent (for instance: http://example.com/form_file.php). This field was required prior to HTML5 but is now optional. : Use this attribute if you want the visitors browser to suggest form responses based on saved entries. The default value is . If you turn autocomplete off you must also turn it off on every field that may allow autocompletion. : Used to specify how form data should be encoded. Only used if the attribute mentioned below is set to . There are three possible values:
- : The default value which replaces all spaces with “+” and converts all special characters to .
- : Nothing is encoded. Input is uploaded to the server exactly as it is entered into the form.
- : Spaces are converted into “+” symbols, but not other characters are encoded.
: Dictates the HTTP method a website visitors browser should use to submit form data. If is specified, form data is enclosed in the body of the HTTP request. If is specified, form data is appended to the end of the URL specified in the attribute with a “?” symbol, data length is limited to 300 characters, and form input is visible and can be bookmarked. : Similar to an attribute, a is a unique identifier that may only be used once within an HTML document and may be used to select the form with JavaScript or another scripting language. : Used to override the default validation of form data. : Specifies where to display the response received after submitting the form.
- loads the response in the same frame.
- opens a new window or tab.
- is used when a form is nested in a descendant browsing context to load the response in the parent context and behaves the same as is there is no parent context.
- is similar to but select the top level browsing context rather than the immediate parent context.
Grouping Form Fields
The element is used to group together related form fields. It may also be used to contain an entire form to provide a visual cue that distinguishes the form from surrounding content. The first element within a is usually a . The will be displayed a part of the border giving website visitors a clue about the purpose of a form. For example, if a contact form were nested within a web page full of otherwise unrelated content, the element could be used in combination with the element to isolate the contact form from the rest of the content both semantically and visually.
When rendered in the browser, the contact form would be clearly separated from surrounding content.
Paragraph content.Contact Form
Additional paragraph content
The element is optional but is commonly used to group related elements on long and complex forms, or to isolate form fields from nearby elements when a form is presented along with non-form content. HTML5 added three attributes which can be applied to elements:
- : Used to disable all of the forms in a fieldset. Note that we used this attribute in the example form above.
- : Used to associate a with the of one or more elements. Note that browser support for this attribute is very limited.
- : Associates a name with the .
List of All Attributes
Attribute | Description |
---|---|
accept-charset | Specifies the character encodings used for form submission |
action | Specifies where to send the form-data when a form is submitted |
autocomplete | Specifies whether a form should have autocomplete on or off |
enctype | Specifies how the form-data should be encoded when submitting it to the server (only for method=»post») |
method | Specifies the HTTP method to use when sending form-data |
name | Specifies the name of the form |
novalidate | Specifies that the form should not be validated when submitted |
rel | Specifies the relationship between a linked resource and the current document |
target | Specifies where to display the response that is received after submitting the form |
❮ Previous
Next ❯
Пример 1. Форма html с кнопками
Преобразуется на странице в следующее:
Пояснения к примеру
- action=»» — говорит о том, что обработка данных будет происходить на этой же странице.
- <input type=»radio» name=»answer» value=»»> — атрибут type=»radio» говорит о том, что нужно отобразить текст после этого кода, как кнопку выбора. Атрибут name и value в данном теге для нас сейчас играют маленькую роль, т.к. мы не изучаем сейчас php (см. уроки php).
- <input type=»text» name=»poletext» value=»»> — атрибут type=»text» говорит о том, что это будет текстовое поле. Здесь так же есть два важных атрибута: name (для php) и value (значение по умолчанию).
- <input type=»textarea» name=»opisanie» value=»»> — атрибут type=»textarea» говорит о том, что это будет большое текстовое поле. Разница от предыдущего случая лишь в том, что он позволяет записывать большой объем текста.
- <input type=»submit» value=»»> — атрибут type=»submit» говорит о том, что это кнопка. В атрибуте value пишется то, что будет написано на кнопке.
Более подробно про все эти элементы можно прочитать в 15 уроке: элементы тега <form>, где рассмотрены радиокнопки, списки, флажки, текстовые поля, кнопки.
Теперь рассмотрим подробно все атрибуты тега <form>.
HTML Reference
HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts
HTML Tags
<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>
Attributes
Attribute | Value | Description |
---|---|---|
accept-charset | character_set | Specifies the character encodings that are to be used for the form submission |
action | URL | Specifies where to send the form-data when a form is submitted |
autocomplete | onoff | Specifies whether a form should have autocomplete on or off |
enctype | application/x-www-form-urlencoded multipart/form-data text/plain |
Specifies how the form-data should be encoded when submitting it to the server (only for method=»post») |
method | get post |
Specifies the HTTP method to use when sending form-data |
name | text | Specifies the name of a form |
novalidate | novalidate | Specifies that the form should not be validated when submitted |
rel | externalhelplicensenextnofollownoopener noreferreropenerprevsearch |
Specifies the relationship between a linked resource and the current document |
target | _blank _self _parent _top |
Specifies where to display the response that is received after submitting the form |
HTML Exercises
List of All <form> Attributes
Attribute | Description |
---|---|
accept-charset | Specifies the character encodings used for form submission |
action | Specifies where to send the form-data when a form is submitted |
autocomplete | Specifies whether a form should have autocomplete on or off |
enctype | Specifies how the form-data should be encoded when submitting it to the server (only for method=»post») |
method | Specifies the HTTP method to use when sending form-data |
name | Specifies the name of the form |
novalidate | Specifies that the form should not be validated when submitted |
rel | Specifies the relationship between a linked resource and the current document |
target | Specifies where to display the response that is received after submitting the form |
❮ Previous
Next ❯
More Examples
Example
<form action=»/action_page.php» method=»get»> <input
type=»checkbox» name=»vehicle1″ value=»Bike»> <label
for=»vehicle1″> I have a bike</label><br> <input type=»checkbox»
name=»vehicle2″ value=»Car»> <label for=»vehicle2″> I have a
car</label><br> <input type=»checkbox» name=»vehicle3″
value=»Boat» checked> <label for=»vehicle3″> I have a
boat</label><br><br> <input type=»submit» value=»Submit»>
</form>
Example
An HTML form with radiobuttons:
<form action=»/action_page.php» method=»get»>
<input type=»radio» id=»html» name=»fav_language» value=»HTML»> <label
for=»html»>HTML</label><br> <input type=»radio» id=»css» name=»fav_language»
value=»CSS» checked=»checked»> <label for=»css»>CSS</label><br>
<input type=»radio» id=»javascript» name=»fav_language» value=»JavaScript»>
<label for=»javascript»>JavaScript</label><br><br> <input
type=»submit» value=»Submit»></form>
HTML Tags
<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>
Атрибуты и свойства тега
1. Атрибут accept-charset=»Кодировка» — определяет кодировку, в которой сервер может принимать и обрабатывать данные формы. Может принимать различные значения, например, CP1251, UTF-8 и т.п.
2. Атрибут action=»URL» — адрес скрипта, который обрабатывает передаваемые данные от формы. Если оставить это значение пустым, то данные будут обрабатываться в этом же документе, где расположена форма.
3. Атрибут autocomplete=»on/off» — задает или отключает автозаполнение формы. Может принимать два значения:
- on — включить автозаполнение;
- off — выключить автозаполнение;
4. Атрибут enctype=»параметр» — задает способ кодирования данных. Может принимать следующие значения:
- application/x-www-form-urlencoded — вместо пробелов ставится +, символы вроде русских букв кодируются их шестнадцатеричными значениями
- multipart/form-data — данные не кодируются
- text/plain — пробелы заменяются знаком +, буквы и другие символы не кодируются.
5. Атрибут method=»POST/GET» — задает метод отправки. Может принимать два значения:
- GET — передача данных в адресной строке (есть ограничение по объёму отправки данных)
- POST — посылает на сервер данные в запросе браузера (может отправить большое количество данных, т.к. нету ограничения объёма)
Более подробное описание методов передачи через GET и POST читайте в уроках по PHP: использование методов GET и POST.
6. Атрибут name=»имя» — задает имя формы. Чаще всего используется в случае наличия множества форм для того, чтобы можно было обратиться к конкретной форме через скрипт.
7. Атрибут novalidate — отменяет встроенную проверку данных формы на корректность ввода.
8. Атрибут target=»параметр» — имя окна или фрейма, куда обработчик будет загружать возвращаемый результат. Может принимать следующие значения:
- _blank — загружает страницу в новое окно браузера
- _self — загружает страницу в текущее окно
- _parent — загружает страницу во фрейм-родитель
- _top — отменяет все фреймы и загружает страницу в полном окне браузера
Уважаемый читатель, теперь Вы узнали гораздо больше о html теге form. Теперь советую перейти к следующему уроку.
Ссылка на следующий урок: Урок 9. HTML тег div — подробное описание с примерами
HTML Tutorial
HTML HOMEHTML IntroductionHTML EditorsHTML BasicHTML ElementsHTML AttributesHTML HeadingsHTML ParagraphsHTML StylesHTML FormattingHTML QuotationsHTML CommentsHTML Colors
Colors
RGB
HEX
HSL
HTML CSSHTML Links
Links
Link Colors
Link Bookmarks
HTML Images
Images
Image Map
Background Images
The Picture Element
HTML Tables
HTML Tables
Table Borders
Table Sizes
Table Headers
Padding & Spacing
Colspan & Rowspan
Table Styling
Table Colgroup
HTML Lists
Lists
Unordered Lists
Ordered Lists
Other Lists
HTML Block & InlineHTML ClassesHTML IdHTML IframesHTML JavaScriptHTML File PathsHTML HeadHTML LayoutHTML ResponsiveHTML ComputercodeHTML SemanticsHTML Style GuideHTML EntitiesHTML SymbolsHTML EmojisHTML CharsetHTML URL EncodeHTML vs. XHTML
The Action Attribute
The attribute defines the action to be performed when the form is submitted.
Usually, the form data is sent to a file on the server when the user clicks on the submit button.
In the example below, the form data is sent to a file called «action_page.php».
This file contains a server-side script that handles the form data:
Example
On submit, send form data to «action_page.php»:
<form action=»/action_page.php»> <label for=»fname»>First
name:</label><br> <input type=»text» id=»fname» name=»fname»
value=»John»><br> <label for=»lname»>Last name:</label><br>
<input type=»text» id=»lname» name=»lname» value=»Doe»><br><br>
<input type=»submit» value=»Submit»></form>
Tip: If the attribute is omitted, the action is set to the current page.
Frequently Asked Questions
How do you restrict a form field to only accept numbers?
In the past, restricting a field to numbers only required the use of JavaScript. However, with the release of HTML5, it’s now simple to limit a field to numeric input only. Just apply the value to the attribute of the applicable element. For example:
When rendered, produces a text input field that will only accept numbers.
How do you restrict a form field to only accept alphanumeric characters?
In the past, the only way to limit field input to alphanumeric characters was to use jQuery or JavaScript and craft a custom function. However, HTML5 added the attribute for elements which can be used to restrict a form field to accept alphanumeric input only. Here’s the code that will do the trick:
In this case, the element will accept lowercase letters, uppercase letters, and numbers. The second part of the value in curly braces stipulates how many total characters may be entered into the field. Let’s see how that looks in the browser.
The way it works is that when you attempt to submit values that don’t meet the specified pattern the attribute is displayed. So you should put some instructions inside the attribute so that users can figure out what they’ve done wrong. Browser support for this relatively new attribute is really pretty good. IE 9 and earlier versions of IE don’t support it and Opera Mini also lacks support. However, all other browsers do support the attribute.
How do you make a form submit when the user presses enter?
If you’ve come across a form that does not submit when you press enter, then someone has intentionally designed the form to behave that way – and they really shouldn’t have done that. are clear: design forms to allow implicit submission. What is implicit submission? Submitting a form by pressing enter. Browsers are designed to support implicit submission. Here’s how it works. Take this form for instance:
If you were focused on any element in that form and pressed enter, the form would be submitted. This is implicit submission and all modern browsers support this behavior. Use the element in the form and you don’t even have to use the value for the attribute. Hit enter while focused on any element in this form and the form will still be submitted.
So how do developers break this behavior? One way to get around this behavior–and to be clear, we don’t recommend this–is to drop the elements. The browser knows what to submit by grouping together everything between the tags. Drop those tags and the browser doesn’t know what to submit. Another way some developers manipulate browser behavior is to use CSS to make buttons rather than proper HTML elements, like this.
Which, when rendered by the browser, would produce a button that looked like a button but did not do anything when enter is pressed.
.submitButton{padding: 10px 20px; margin-top: 10px; background-color: #ddd; border-radius: 5px; display: inline-block;}.submitButton:hover{background-color: #ccc;}.submitButton:active{background-color: #ddd;} Name: Age: Submit
Usually, developers have good intentions when they do things like this. Typically, what they’re trying to do is tie form validation to an JavaScript event. Form validation is a good thing, but creating a barrier to accessibility in the name of form validation is not a good thing. So, what should you do instead of disabling implicit submission? Leave implicit submission intact and use JavaScript to add an event listener to each field. Use the event listener to trigger form validation like this.
That code leaves implicit submission intact, but still runs validation code when the user presses enter.
Jon Penland
The Method Attribute
The attribute specifies the HTTP
method to be used when submitting the form data.
The form-data can be sent as URL variables (with )
or as HTTP post transaction (with ).
The default HTTP method when submitting form data is GET.
Example
This example uses the GET method when submitting the form data:
<form action=»/action_page.php» method=»get»>
Example
This example uses the POST method when submitting the form data:
<form action=»/action_page.php» method=»post»>
Notes on GET:
- Appends the form data to the URL, in name/value pairs
- NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
- The length of a URL is limited (2048 characters)
- Useful for form submissions where a user wants to bookmark the result
- GET is good for non-secure data, like query strings in Google
Notes on POST:
- Appends the form data inside the body of the HTTP request (the submitted
form data is not shown in the URL) - POST has no size limitations, and can be used to send large amounts of data.
- Form submissions with POST cannot be bookmarked
Tip: Always use POST if the form data contains sensitive or personal information!