1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
|
---
title: Your first form
slug: Learn/HTML/Forms/Your_first_form
translation_of: Learn/Forms/Your_first_form
---
<div>{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}</div>
<p class="summary">Першa стаття в нашій серії допоможе вам у створенні власної першої інтернет-форми, включаючи розробку простої форми, реалізуючи її за допомогою використання елементів керування формою в HTML і інших HTML елементів, добавляючи деякі дуже прості стилі в CSS, і обписуючи як дані надсилаються на сервер. В цьому модулі ми розгорнемо кожну з вищенаведених тем.</p>
<table class="learn-box standard-table">
<tbody>
<tr>
<th scope="row">Вимоги:</th>
<td>Загальна комп'ютерна грамотність, і базове <a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">розуміння HTML</a>.</td>
</tr>
<tr>
<th scope="row">Мета:</th>
<td>Зрозуміти, що таке інтернет-форми, для чого вони використовується, як обдумувати їхнє оформлення, і основні HTML елементи, які потрібні в нескладних випадках</td>
</tr>
</tbody>
</table>
<h2 id="Що_таке_інтернет-форми">Що таке інтернет-форми?</h2>
<p><strong>Web forms</strong> are one of the main points of interaction between a user and a web site or application. Forms allow users to enter data, which is generally sent to a web server for processing and storage (see <a href="/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data">Sending form data</a> later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature).</p>
<p>A<strong> </strong>web form's HTML is made up of one or more <strong>form controls</strong> (sometimes called <strong>widgets</strong>), plus some additional elements to help structure the overall form — they are often referred to as <strong>HTML forms</strong>. The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the {{htmlelement("input")}} element, although there are some other elements to learn about too.</p>
<p>Form controls can also be programmed to enforce specific formats or values to be entered (<strong>form validation</strong>), and paired with text labels that describe their purpose to both sighted and blind users.</p>
<h2 id="Designing_your_form">Designing your form</h2>
<p>Before starting to code, it's always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need.</p>
<p>Designing forms is an important step when you are building a site or application. It's beyond the scope of this article to cover the user experience of forms, but if you want to dig into that topic you should read the following articles:</p>
<ul>
<li>Smashing Magazine has some <a href="https://www.smashingmagazine.com/2018/08/ux-html5-mobile-form-part-1/" rel="external" title="http://uxdesign.smashingmagazine.com/tag/forms/">good articles about forms UX</a>, including an older but still relevant <a href="https://www.smashingmagazine.com/2011/11/extensive-guide-web-form-usability/" rel="external" title="http://uxdesign.smashingmagazine.com/2011/11/08/extensive-guide-web-form-usability/">Extensive Guide To Web Form Usability</a> article.</li>
<li>UXMatters is also a very thoughtful resource with good advice from <a href="http://www.uxmatters.com/mt/archives/2012/05/7-basic-best-practices-for-buttons.php" rel="external" title="http://www.uxmatters.com/mt/archives/2012/05/7-basic-best-practices-for-buttons.php">basic best practices</a> to complex concerns such as <a href="http://www.uxmatters.com/mt/archives/2010/03/pagination-in-web-forms-evaluating-the-effectiveness-of-web-forms.php" title="http://www.uxmatters.com/mt/archives/2010/03/pagination-in-web-forms-evaluating-the-effectiveness-of-web-forms.php">multi-page forms</a>.</li>
</ul>
<p>In this article, we'll build a simple contact form. Let's make a rough sketch.</p>
<p><img alt="The form to build, roughly sketch" src="/files/4579/form-sketch-low.jpg" style="border-style: solid; border-width: 1px; display: block; height: 352px; margin: 0px auto; width: 400px;"></p>
<p>Our form will contain three text fields and one button. We are asking the user for their name, their e-mail and the message they want to send. Hitting the button will send their data to a web server.</p>
<h2 id="Active_learning_Implementing_our_form_HTML">Active learning: Implementing our form HTML</h2>
<p>Ok, let's have a go at creating the HTML for our form. We will use the following HTML elements: {{HTMLelement("form")}}, {{HTMLelement("label")}}, {{HTMLelement("input")}}, {{HTMLelement("textarea")}}, and {{HTMLelement("button")}}.</p>
<p>Before you go any further, make a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/html/introduction-to-html/getting-started/index.html">simple HTML template</a> — you'll enter your form HTML into here.</p>
<h3 id="The_HTMLelementform_element">The {{HTMLelement("form")}} element</h3>
<p>All forms start with a {{HTMLelement("form")}} element, like this:</p>
<pre class="brush:html;"><form action="/my-handling-form-page" method="post">
</form></pre>
<p>This element formally defines a form. It's a container element like a {{HTMLelement("section")}} or {{HTMLelement("footer")}} element, but specifically for containing forms; it also supports some specific attributes to configure the way the form behaves. All of its attributes are optional, but it's standard practice to always set at least the <a href="/en-US/docs/Web/HTML/Attributes/action"><code>action</code></a> and <a href="/en-US/docs/Web/HTML/Attributes/method"><code>method</code></a> attributes:</p>
<ul>
<li>The <code>action</code> attribute defines the location (URL) where the form's collected data should be sent when it is submitted.</li>
<li>The <code>method</code> attribute defines which HTTP method to send the data with (usually <code>get</code> or <code>post</code>).</li>
</ul>
<div class="note">
<p><strong>Note</strong>: We'll look at how those attributes work in our <a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data">Sending form data</a> article later on.</p>
</div>
<p>For now, add the above {{htmlelement("form")}} element into your HTML {{htmlelement("body")}}.</p>
<h3 id="The_HTMLelementlabel_HTMLelementinput_and_HTMLelementtextarea_elements">The {{HTMLelement("label")}}, {{HTMLelement("input")}}, and {{HTMLelement("textarea")}} elements</h3>
<p>Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding {{HTMLelement("label")}}:</p>
<ul>
<li>The input field for the name is a {{HTMLelement("input/text", "single-line text field")}}.</li>
<li>The input field for the e-mail is an {{HTMLelement("input/email", "input of type email")}}: a single-line text field that accepts only e-mail addresses.</li>
<li>The input field for the message is a {{HTMLelement("textarea")}}; a multiline text field.</li>
</ul>
<p>In terms of HTML code we need something like the following to implement these form widgets:</p>
<pre class="brush:html;" dir="rtl"><form action="/my-handling-form-page" method="post">
<ul>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</li>
<li>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_mail">
</li>
<li>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</li>
</ul>
</form></pre>
<p>Update your form code to look like the above.</p>
<p>The {{HTMLelement("li")}} elements are there to conveniently structure our code and make styling easier (see later in the article). For usability and accessibility, we include an explicit label for each form control. Note the use of the<a href="/en-US/docs/Web/HTML/Attributes/for"> <code>for</code> </a>attribute on all {{HTMLelement("label")}} elements, which takes as its value the <a href="/en-US/docs/Web/HTML/Attributes/id"><code>id</code></a> of the form control with which it is associated — this is how you associate a form with its label.</p>
<p>There is great benefit to doing this — it associates the label with the form control, enabling mouse, trackpad, and touch device users to click on the label to activate the corresponding control, and it also provides an accessible name for screen readers to read out to their users. You'll find further details of form labels in <a href="/en-US/docs/Learn/Forms/How_to_structure_a_web_form">How to structure a web form</a>.</p>
<p>On the {{HTMLelement("input")}} element, the most important attribute is the <code>type</code> attribute. This attribute is extremely important because it defines the way the {{HTMLelement("input")}} element appears and behaves. You'll find more about this in the <a href="/en-US/docs/Learn/Forms/Basic_native_form_controls">Basic native form controls</a> article later on.</p>
<ul>
<li>In our simple example, we use the value {{HTMLelement("input/text")}} for the first input — the default value for this attribute. It represents a basic single-line text field that accepts any kind of text input.</li>
<li>For the second input, we use the value {{HTMLelement("input/email")}}, which defines a single-line text field that only accepts a well-formed e-mail address. This turns a basic text field into a kind of "intelligent" field that will perform some validation checks on the data typed by the user. It also causes a more appropriate keyboard layout for entering email addresses (e.g. with an @ symbol by default) to appear on devices with dynamic keyboards, like smartphones. You'll find out more about form validation in the <a href="/en-US/docs/Learn/Forms/Form_validation">client-side form validation</a> article later on.</li>
</ul>
<p>Last but not least, note the syntax of <code><input></code> vs. <code><textarea></textarea></code>. This is one of the oddities of HTML. The <code><input></code> tag is an empty element, meaning that it doesn't need a closing tag. {{HTMLElement("textarea")}} is not an empty element, meaning it should be closed it with the proper ending tag. This has an impact on a specific feature of forms: the way you define the default value. To define the default value of an {{HTMLElement("input")}} element you have to use the <a href="/en-US/docs/Web/HTML/Attributes/value"><code>value</code></a> attribute like this:</p>
<pre class="brush:html;"><input type="text" value="by default this element is filled with this text"></pre>
<p>On the other hand, if you want to define a default value for a {{HTMLElement("textarea")}}, you put it between the opening and closing tags of the {{HTMLElement("textarea")}} element, like this:</p>
<pre class="brush:html;"><textarea>
by default this element is filled with this text
</textarea></pre>
<h3 id="The_HTMLelementbutton_element">The {{HTMLelement("button")}} element</h3>
<p>The markup for our form is almost complete; we just need to add a button to allow the user to send, or "submit", their data once they have filled out the form. This is done by using the {{HTMLelement("button")}} element; add the following just above the closing <code></form></code> tag:</p>
<pre class="brush:html;"><li class="button">
<button type="submit">Send your message</button>
</li></pre>
<p>The {{htmlelement("button")}} element also accepts a <code>type</code> attribute — this accepts one of three values: <code>submit</code>, <code>reset</code>, or <code>button</code>.</p>
<ul>
<li>A click on a <code>submit</code> button (the default value) sends the form's data to the web page defined by the <code>action</code> attribute of the {{HTMLelement("form")}} element.</li>
<li>A click on a <code>reset</code> button resets all the form widgets to their default value immediately. From a UX point of view, this is considered bad practice, so you should avoid using this type of button unless you really have a good reason to include one.</li>
<li>A click on a <code>button</code> button does... nothing! That sounds silly, but it's amazingly useful for building custom buttons — you can define their chosen functionality with JavaScript.</li>
</ul>
<div class="note">
<p><strong>Note</strong>: You can also use the {{HTMLElement("input")}} element with the corresponding <code>type</code> to produce a button, for example <code><input type="submit"></code>. The main advantage of the {{HTMLelement("button")}} element is that the {{HTMLelement("input")}} element only allows plain text in its label whereas the {{HTMLelement("button")}} element allows full HTML content, allowing more complex, creative button content.</p>
</div>
<h2 id="Basic_form_styling">Basic form styling</h2>
<p>Now that you have finished writing your form's HTML code, try saving it and looking at it in a browser. At the moment, you'll see that it looks rather ugly.</p>
<div class="note">
<p><strong>Note</strong>: If you don't think you've got the HTML code right, try comparing it with our finished example — see <a href="https://github.com/mdn/learning-area/blob/master/html/forms/your-first-HTML-form/first-form.html">first-form.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/your-first-HTML-form/first-form.html">also see it live</a>).</p>
</div>
<p>Forms are notoriously tricky to style nicely. It is beyond the scope of this article to teach you form styling in detail, so for the moment we will just get you to add some CSS to make it look OK.</p>
<p>First of all, add a {{htmlelement("style")}} element to your page, inside your HTML head. It should look like so:</p>
<pre class="brush: html"><style>
</style></pre>
<p>Inside the <code>style</code> tags, add the following CSS:</p>
<pre class="brush:css;">form {
/* Center the form on the page */
margin: 0 auto;
width: 400px;
/* Form outline */
padding: 1em;
border: 1px solid #CCC;
border-radius: 1em;
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
form li + li {
margin-top: 1em;
}
label {
/* Uniform size & alignment */
display: inline-block;
width: 90px;
text-align: right;
}
input,
textarea {
/* To make sure that all text fields have the same font settings
By default, textareas have a monospace font */
font: 1em sans-serif;
/* Uniform text field size */
width: 300px;
box-sizing: border-box;
/* Match form field borders */
border: 1px solid #999;
}
input:focus,
textarea:focus {
/* Additional highlight for focused elements */
border-color: #000;
}
textarea {
/* Align multiline text fields with their labels */
vertical-align: top;
/* Provide space to type some text */
height: 5em;
}
.button {
/* Align buttons with the text fields */
padding-left: 90px; /* same size as the label elements */
}
button {
/* This extra margin represent roughly the same space as the space
between the labels and their text fields */
margin-left: .5em;
}</pre>
<p>Save and reload, and you'll see that your form should look much less ugly.</p>
<div class="note">
<p><strong>Note</strong>: You can find our version on GitHub at <a href="https://github.com/mdn/learning-area/blob/master/html/forms/your-first-HTML-form/first-form-styled.html">first-form-styled.html</a> (<a href="https://mdn.github.io/learning-area/html/forms/your-first-HTML-form/first-form-styled.html">also see it live</a>).</p>
</div>
<h2 id="Sending_form_data_to_your_web_server">Sending form data to your web server</h2>
<p>The last part, and perhaps the trickiest, is to handle form data on the server side. The {{HTMLelement("form")}} element defines where and how to send the data thanks to the <a href="/en-US/docs/Web/HTML/Attributes/action"><code>action</code></a> and <a href="/en-US/docs/Web/HTML/Attributes/method"><code>method</code></a> attributes.</p>
<p>We provide a <a href="/en-US/docs/Web/HTML/Attributes/name"><code>name</code></a> to each form control. The names are important on both the client- and server-side; they tell the browser which name to give each piece of data and, on the server side, they let the server handle each piece of data by name. The form data is sent to the server as name/value pairs.</p>
<p>To name the data in a form you need to use the <code>name</code> attribute on each form widget that will collect a specific piece of data. Let's look at some of our form code again:</p>
<pre class="brush:html;"><form action="/my-handling-form-page" method="post">
<ul>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name" />
</li>
<li>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_email" />
</li>
<li>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</li>
...
</pre>
<p>In our example, the form will send 3 pieces of data named "<code>user_name</code>", "<code>user_email</code>", and "<code>user_message</code>". That data will be sent to the URL "<code>/my-handling-form-page</code>" using the <a href="/en-US/docs/Web/HTTP/Methods/POST">HTTP <code>POST</code></a> method.</p>
<p>On the server side, the script at the URL "<code>/my-handling-form-page</code>" will receive the data as a list of 3 key/value items contained in the HTTP request. The way this script will handle that data is up to you. Each server-side language (PHP, Python, Ruby, Java, C#, etc.) has its own mechanism of handling form data. It's beyond the scope of this guide to go deeply into that subject, but if you want to know more, we have provided some examples in our <a href="/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data" title="/en-US/docs/HTML/Forms/Sending_and_retrieving_form_data"><span>Sending form data</span></a> article later on.</p>
<h2 id="Summary">Summary</h2>
<p>Congratulations, you've built your first web form. It looks like this live:</p>
<p>{{ EmbedLiveSample('A_simple_form', '100%', '240', '', 'Learn/Forms/Your_first_form/Example') }}</p>
<p>That's only the beginning, however — now it's time to take a deeper look. Forms have way more power than what we saw here and the other articles in this module will help you to master the rest.</p>
<p>{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}</p>
<h2 id="In_this_module">In this module</h2>
<ul>
<li><a href="/en-US/docs/Learn/Forms/Your_first_form">Your first form</a></li>
<li><a href="/en-US/docs/Learn/Forms/How_to_structure_a_web_form">How to structure a web form</a></li>
<li><a href="/en-US/docs/Learn/Forms/Basic_native_form_controls">Basic native form controls</a></li>
<li><a href="/en-US/docs/Learn/Forms/HTML5_input_types">The HTML5 input types</a></li>
<li><a href="/en-US/docs/Learn/Forms/Other_form_controls">Other form controls</a></li>
<li><a href="/en-US/docs/Learn/Forms/Styling_web_forms">Styling web forms</a></li>
<li><a href="/en-US/docs/Learn/Forms/Advanced_form_styling">Advanced form styling</a></li>
<li><a href="/en-US/docs/Learn/Forms/UI_pseudo-classes">UI pseudo-classes</a></li>
<li><a href="/en-US/docs/Learn/Forms/Form_validation">Client-side form validation</a></li>
<li><a href="/en-US/docs/Learn/Forms/Sending_and_retrieving_form_data">Sending form data</a></li>
</ul>
<h3 id="Advanced_Topics">Advanced Topics</h3>
<ul>
<li><a href="/en-US/docs/Learn/Forms/How_to_build_custom_form_controls">How to build custom form controls</a></li>
<li><a href="/en-US/docs/Learn/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li>
<li><a href="/en-US/docs/Learn/Forms/Property_compatibility_table_for_form_widgets">Property compatibility table for form widgets</a></li>
</ul>
|