From ebe0e1bc9a1bd02ed909caedc91648e79677e35a Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:48:38 +0100 Subject: unslug my: move --- files/my/learn/forms/html5_input_types/index.html | 276 +++++++++++++++++++ files/my/learn/forms/index.html | 83 ++++++ files/my/learn/forms/your_first_form/index.html | 298 +++++++++++++++++++++ .../learn/html/forms/html5_input_types/index.html | 276 ------------------- files/my/learn/html/forms/index.html | 83 ------ .../my/learn/html/forms/your_first_form/index.html | 298 --------------------- 6 files changed, 657 insertions(+), 657 deletions(-) create mode 100644 files/my/learn/forms/html5_input_types/index.html create mode 100644 files/my/learn/forms/index.html create mode 100644 files/my/learn/forms/your_first_form/index.html delete mode 100644 files/my/learn/html/forms/html5_input_types/index.html delete mode 100644 files/my/learn/html/forms/index.html delete mode 100644 files/my/learn/html/forms/your_first_form/index.html diff --git a/files/my/learn/forms/html5_input_types/index.html b/files/my/learn/forms/html5_input_types/index.html new file mode 100644 index 0000000000..74b3202f26 --- /dev/null +++ b/files/my/learn/forms/html5_input_types/index.html @@ -0,0 +1,276 @@ +--- +title: The HTML5 input types +slug: Learn/HTML/Forms/HTML5_input_types +translation_of: Learn/Forms/HTML5_input_types +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}
+ +

In the previous article we looked at the {{htmlelement("input")}} element, covering the original values of the type attribute available since the early days of HTML. Now we'll look at the functionality of newer form controls in detail, including some new input types, which were added in HTML5 to allow collection of specific types of data.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, and a basic understanding of HTML.
Objective:To understand the newer input type values available to create native form controls, and how to implement them using HTML.
+ +
+

Note: Most of the features discussed in this article have wide support across browsers. We'll note any exceptions. If you want more detail on browser support, you should consult our HTML forms element reference, and in particular our extensive <input> types reference.

+
+ +

Because HTML form control appearance may be quite different from a designer's specifications, web developers sometimes build their own custom form controls. We cover this in an advanced tutorial — How to build custom form widgets.

+ +

E-mail address field

+ +

This type of field is set using the value email for the {{htmlattrxref("type","input")}} attribute:

+ +
<input type="email" id="email" name="email">
+ +

When this {{htmlattrxref("type","input")}} is used, the user is required to type a valid email address into the field. Any other content causes the browser to display an error when the form is submitted. You can see this in action in the below screenshot.

+ +

An invalid email input showing the message "Please enter an email address."

+ +

You can also use the multiple attribute in combination with the email input type to allow several email addresses to be entered in the same input (separated by commas):

+ +
<input type="email" id="email" name="email" multiple>
+ +

On some devices — notably, touch devices with dynamic keyboards like smart phones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. See the Firefox for Android keyboard screenshot below for an example:

+ +

firefox for android email keyboard, with ampersand displayed by default.

+ +
+

Note: You can find examples of the basic text input types at basic input examples (see the source code also).

+
+ +

This is another good reason for using these newer input types — improving the user experience for users of these devices.

+ +

Client-side validation

+ +

As you can see above, email, along with other newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. It is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server.

+ +

But it should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind.

+ +

Note that a@b is a valid email address according to the default provided constraints. This is because the email input type allows intranet email addresses by default. To implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the Client-side form validation article later on.

+ +
+

Note: If the data entered is not an email address, the {{cssxref(':invalid')}} pseudo-class will match, and the {{domxref('validityState.typeMismatch')}} property will return true.

+
+ +

Search field

+ +

Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value search for the {{htmlattrxref("type","input")}} attribute:

+ +
<input type="search" id="search" name="search">
+ +

The main difference between a text field and a search field is how the browser styles its appearance.  Often, search fields are rendered with rounded corners; they also sometimes display an "Ⓧ", which clears the field of any value when clicked). Additionally, on devices with dynamic keyboards, the keyboard's enter key may read "search", or display a magnifying glass icon.

+ +

The below screenshots show a non-empty search field in Firefox 71, Safari 13, and Chrome 79 on macOS, and Edge 18 and Chrome 79 on Windows 10. Note the clear icon only appears if the field has a value, and, apart from Safari, it is only displayed when the field is focused.

+ +

Screenshots of search fields on several platforms.

+ +

Another feature worth noting is that the values of a search field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website. This tends to happen automatically in most modern browsers.

+ +

Phone number field

+ +

A special field for filling in phone numbers can be created using tel as the value of the {{htmlattrxref("type","input")}} attribute:

+ +
<input type="tel" id="tel" name="tel">
+ +

When accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when type="tel" is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers.

+ +

The following Firefox for Android keyboard screenshot provides an example:

+ +

firefox for android email keyboard, with ampersand displayed by default.

+ +

Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user. (This means it may include letters, etc.).

+ +

As we mentioned earlier, The pattern attribute can be used to enforce constraints, which you'll learn about in Client-side form validation.

+ +

URL field

+ +

A special type of field for entering URLs can be created using the value url for the {{htmlattrxref("type","input")}} attribute:

+ +
<input type="url" id="url" name="url">
+ +

It adds special validation constraints to the field. The browser will report an error if no protocol (such as http:) is entered, or if the URL is otherwise malformed. On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys.

+ +

See below for an example (taken on Fireox for Android):

+ +

firefox for android email keyboard, with ampersand displayed by default.

+ +
Note: Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists!
+ +

Numeric field

+ +

Controls for entering numbers can be created with an {{HTMLElement("input")}} {{htmlattrxref("type","input")}} of number. This control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. On devices with dynamic keyboards, the numeric keyboard is generally displayed.

+ +

The following screenshot (from Firefox for Android) provides an example:

+ +

firefox for android email keyboard, with ampersand displayed by default.

+ +

With the number input type, you can constrain the minimum and maximum values allowed by setting the {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} attributes.

+ +

You can also use the step attribute to set the increment increase and decrease caused by pressing the spinner buttons. By default, the number input type only validates if the number is an integer. To allow float numbers, specify step="any". If omitted, the step value defaults to 1, meaning only whole numbers are valid.

+ +

Let's look at some examples. The first one below creates a number control whose value is restricted to any value between 1 and 10, and whose increase and decrease buttons change its value by 2.

+ +
<input type="number" name="age" id="age" min="1" max="10" step="2">
+ +

The second one creates a number control whose value is restricted to any value between 0 and 1 inclusive, and whose increase and decrease buttons change its value by 0.01.

+ +
<input type="number" name="change" id="pennies" min="0" max="1" step="0.01">
+ +

The number input type makes sense when the range of valid values is limited, for example a person's age or height. If the range is too large for incremental increases to make sense (such as USA ZIP codes, which range from 00001 to 99999), the tel type might be a better option; it provides the numeric keypad while forgoing the number's spinner UI feature.

+ +
+

Note: number inputs are not supported in versions of Internet Explorer below 10.

+
+ +

Slider controls

+ +

Another way to pick a number is to use a slider. You see these quite often on sites like housebuying sites where you want to set a maximum property price to filter by. Let's look at a live example to illustrate this:

+ +

{{EmbedGHLiveSample("learning-area/html/forms/range-example/index.html", '100%', 200)}}

+ +

Usage-wise, sliders are less accurate than text fields. Therefore, they are used to pick a number whose precise value is not necessarily important.

+ +

A slider is created using the {{HTMLElement("input")}} with its {{htmlattrxref("type","input")}} attribute set to the value range. The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad.

+ +

It's important to properly configure your slider. To that end, it's highly recommended that you set the min, max, and step attributes which set the minimum, maximum and increment values, respectively.

+ +

Let's look at the code behind the above example, so you can see how its done. First of all, the basic HTML:

+ +
<label for="price">Choose a maximum house price: </label>
+<input type="range" name="price" id="price" min="50000" max="500000" step="100" value="250000">
+<output class="price-output" for="price"></output>
+ +

This example creates a slider whose value may range between 50000 and 500000, which increments/decrements by 100 at a time. We've given it default value of 250000, using the value attribute.

+ +

One problem with sliders is that they don't offer any kind of visual feedback as to what the current value is. This is why we've included an {{htmlelement("output")}} element — to contain the current value (we'll also look at this element in the next article). You could display an input value or the output of a calculation inside any element, but <output> is special — like <label>, it can take a for attribute that allows you to associate it with the element or elements that the output value came from.

+ +

To actually display the current value, and update it as it changed, you must use JavaScript, but this is relatively easy to do:

+ +
const price = document.querySelector('#price')
+const output = document.querySelector('.price-output')
+
+output.textContent = price.value
+
+price.addEventListener('input', function() {
+  output.textContent = price.value
+});
+ +

Here we store references to the range input and the output in two variables. Then we immediately set the output's textContent to the current value of the input. Finally, an event listener is set to ensure that whenever the range slider is moved, the output's textContent is updated to the new value.

+ +
+

Note: range inputs are not supported in versions of Internet Explorer below 10.

+
+ +

Date and time pickers

+ +

Gathering date and time values has traditionally been a nightmare for web developers. For good user experience, it is important to provide a calendar selection UI, enabling users to select dates without necessating context switching to a native calendar application or potentially entering them in differing formats that are hard to parse. The last minute of the previous millenium can be expressed in the following different ways, for example: 1999/12/31, 23:59 or 12/31/99T11:59PM.

+ +

HTML date controls are available to handle this specific kind of data, providing calendar widgets and making the data uniform.

+ +

A date and time control is created using the {{HTMLElement("input")}} element and an appropriate value for the {{htmlattrxref("type","input")}} attribute, depending on whether you wish to collect dates, times, or both. Here's a live example that falls back to {{htmlelement("select")}} elements in non-supporting browsers:

+ +

{{EmbedGHLiveSample("learning-area/html/forms/datetime-local-picker-fallback/index.html", '100%', 200)}}

+ +

Let's look at the different available types in brief. Note that the usage of these types is quite complex, especially considering browser support (see below); to find out the full details, follow the links below to the reference pages for each type, including detailed examples.

+ +

datetime-local

+ +

<input type="datetime-local"> creates a widget to display and pick a date with time with no specific time zone information.

+ +
<input type="datetime-local" name="datetime" id="datetime">
+ +

month

+ +

<input type="month"> creates a widget to display and pick a month with a year.

+ +
<input type="month" name="month" id="month">
+ +

time

+ +

<input type="time"> creates a widget to display and pick a time value. While time may display in 12-hour format, the value returned is in 24-hour format.

+ +
<input type="time" name="time" id="time">
+ +

week

+ +

<input type="week"> creates a widget to display and pick a week number and its year.

+ +

Weeks start on Monday and run to Sunday. Additionally, the first week 1 of each year contains the first Thursday of that year—which may not include the first day of the year, or may include the last few days of the previous year.

+ +
<input type="week" name="week" id="week">
+ +

Constraining date/time values

+ +

All date and time controls can be constrained using the min and max attributes, with further constraining possible via the step attribute (whose value is given in seconds).

+ +
<label for="myDate">When are you available this summer?</label>
+<input type="date" name="myDate" min="2013-06-01" max="2013-08-31" step="3600" id="myDate">
+ +

Browser support for date/time inputs

+ +

You should be warned that the date and time widgets don't have the best browser support. At the moment, Chrome, Edge, and Opera support them well, but there is no support in Internet Explorer, Safari has some mobile support (but no desktop support), and Firefox supports time and date only.

+ +

The reference pages linked to above provide suggestions on how to program fallbacks for non-supporting browsers; another option is to consider using a JavaScript library to provide a date picker. Most modern frameworks have good components available to provide this functionality, and there are standalone libraries available to (see Top date picker javascript plugins and libraries for some suggestions).

+ +

Color picker control

+ +

Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, etc.

+ +

A color control can be created using the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value color:

+ +
<input type="color" name="color" id="color">
+ +

When supported, clicking a color control will tend to display the operating system's default color picking functionality for you to actually make your choice with. The following screenshot taken on Firefox for macOS provides an example:

+ +

firefox for android email keyboard, with ampersand displayed by default.

+ +

And here is a live example for you to try out:

+ +

{{EmbedGHLiveSample("learning-area/html/forms/color-example/index.html", '100%', 200)}}

+ +

The value returned is always a lowercase 6-value hexidecimal color.

+ +
+

Note: color inputs are not supported in Internet Explorer.

+
+ +

Summary

+ +

That brings us to the end of our tour of the HTML5 form input types. There are a few other control types that cannot be easily grouped together due to their very specific behaviors, but which are still essential to know about. We cover those in the next article.

+ +

{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}

+ +

In this module

+ + + +

Advanced Topics

+ + diff --git a/files/my/learn/forms/index.html b/files/my/learn/forms/index.html new file mode 100644 index 0000000000..215164d6a6 --- /dev/null +++ b/files/my/learn/forms/index.html @@ -0,0 +1,83 @@ +--- +title: HTML forms +slug: Learn/HTML/Forms +tags: + - Beginner + - Featured + - Forms + - Guide + - HTML + - Landing + - Learn + - NeedsTranslation + - TopicStub + - Web +translation_of: Learn/Forms +--- +
{{LearnSidebar}}
+ +

This module provides a series of articles that will help you master HTML forms. HTML forms are a very powerful tool for interacting with users; however, for historical and technical reasons, it's not always obvious how to use them to their full potential. In this guide, we'll cover all aspects of HTML forms, from structure to styling, from data handling to custom widgets.

+ +

Prerequisites

+ +

Before starting this module, you should at least work through our Introduction to HTML. At this point you should find the {{anch("Basic guides")}} easy to understand, and also be able to make use of our Native form widgets guide.

+ +

The rest of the module however is a bit more advanced — it is easy to put form widgets on a page, but you can't actually do much with them without using some advanced form features, CSS, and JavaScript. Therefore, before you look at the other sections we'd recommend that you go away and learn some CSS and JavaScript first.

+ +
+

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Basic guides

+ +
+
Your first HTML form
+
The first article in our series provides your very first experience of creating an HTML form, including designing a simple form, implementing it using the right HTML elements, adding some very simple styling via CSS, and how data is sent to a server.
+
How to structure an HTML form
+
With the basics out of the way, we now look in more detail at the elements used to provide structure and meaning to the different parts of a form.
+
+ +

What form widgets are available?

+ +
+
The native form widgets
+
We now look at the functionality of the different form widgets in detail, looking at what options are available to collect different types of data.
+
+ +

Validating and submitting form data

+ +
+
Sending form data
+
This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.
+
Form data validation
+
Sending data is not enough — we also need to make sure that the data users fill out in forms is in the correct format we need to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and don't get frustrated when trying to use our apps. Form validation helps us achieve these goals — this article tells you what you need to know.
+
+ +

Advanced guides

+ +
+
How to build custom form widgets
+
You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study.
+
Sending forms through JavaScript
+
This article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.)
+
HTML forms in legacy browsers
+
Article covering feature detection, etc. This should be redirected to the cross browser testing module, as the same stuff is covered better there.
+
+ +

Form styling guides

+ +
+
Styling HTML forms
+
This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.
+
Advanced styling for HTML forms
+
Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style elements.
+
Property compatibility table for form widgets
+
This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.
+
+ +

See also

+ + diff --git a/files/my/learn/forms/your_first_form/index.html b/files/my/learn/forms/your_first_form/index.html new file mode 100644 index 0000000000..03f72249e9 --- /dev/null +++ b/files/my/learn/forms/your_first_form/index.html @@ -0,0 +1,298 @@ +--- +title: ပထမဆုံး Form +slug: Learn/HTML/Forms/Your_first_form +translation_of: Learn/Forms/Your_first_form +--- +
{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
+ +

Web form တစ်ခုဖန်တီးဖို့အတွက် ပထမဆုံးအတွေ့အကြုံကို ဆောင်းပါးစီးရီးရဲ့ ပထမဦးဆုံးသော ဒီဆောင်းပါးမှာ ရရှိမှာပါ။,  HTML form controls တွေနဲ့ အခြား HTML elements တွေကိုမှန်ကန်စွာအသုံးချပြီး ရိုးရိုး form တစ်ခုကို ဒီဇိုင်းပုံဖော်ခြင်းနဲ့ လက်တွေ့ရေးဆွဲရပါမယ်။ CSS ကိုသုံးပြီး အဲဒီ Form ကို ရိုးရိုးလေး အလှဆင်တာနည်းနည်းလုပ်ရမယ်။ ဆာဗာကို ဒေတာတွေဘယ်လိုပို့သလဲဆိုတာလည်း လေ့လာရပါမယ်။ အပေါ်မှာပြောခဲ့တာတွေ တစ်ခုချင်းစီကို နောက်ပိုင်းမှာ နည်းနည်းပိုပြီးအသေးစိတ်ရှင်းပြပေးသွားပါမယ်။

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, and a basic understanding of HTML.
Objective:To gain familiarity with what web forms are, what they are used for, how to think about designing them, and the basic HTML elements you'll need for simple cases.
+ +

What are web forms?

+ +

Web forms 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 Sending form data 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).

+ +

A web form's HTML is made up of one or more form controls (sometimes called widgets), plus some additional elements to help structure the overall form — they are often referred to as HTML forms. 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.

+ +

Form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users.

+ +

Designing your form

+ +

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.

+ +

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:

+ + + +

In this article, we'll build a simple contact form. Let's make a rough sketch.

+ +

The form to build, roughly sketch

+ +

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.

+ +

Active learning: Implementing our form HTML

+ +

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")}}.

+ +

Before you go any further, make a local copy of our simple HTML template — you'll enter your form HTML into here.

+ +

The {{HTMLelement("form")}} element

+ +

All forms start with a {{HTMLelement("form")}} element, like this:

+ +
<form action="/my-handling-form-page" method="post">
+
+</form>
+ +

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 action and method attributes:

+ + + +
+

Note: We'll look at how those attributes work in our Sending form data article later on.

+
+ +

For now, add the above {{htmlelement("form")}} element into your HTML {{htmlelement("body")}}.

+ +

The {{HTMLelement("label")}}, {{HTMLelement("input")}}, and {{HTMLelement("textarea")}} elements

+ +

Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding {{HTMLelement("label")}}:

+ + + +

In terms of HTML code we need something like the following to implement these form widgets:

+ +
<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>
+ </ul>
+</form>
+ +

Update your form code to look like the above.

+ +

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 for attribute on all {{HTMLelement("label")}} elements, which takes as its value the id of the form control with which it is associated — this is how you associate a form control with its label.

+ +

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 How to structure a web form.

+ +

On the {{HTMLelement("input")}} element, the most important attribute is the type 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 Basic native form controls article later on.

+ + + +

Last but not least, note the syntax of <input> vs. <textarea></textarea>. This is one of the oddities of HTML. The <input> 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 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 value attribute like this:

+ +
<input type="text" value="by default this element is filled with this text">
+ +

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:

+ +
<textarea>
+by default this element is filled with this text
+</textarea>
+ +

The {{HTMLelement("button")}} element

+ +

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 </ul> tag:

+ +
<li class="button">
+  <button type="submit">Send your message</button>
+</li>
+ +

The {{htmlelement("button")}} element also accepts a type attribute — this accepts one of three values: submit, reset, or button.

+ + + +
+

Note: You can also use the {{HTMLElement("input")}} element with the corresponding type to produce a button, for example <input type="submit">. 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.

+
+ +

Basic form styling

+ +

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.

+ +
+

Note: If you don't think you've got the HTML code right, try comparing it with our finished example — see first-form.html (also see it live).

+
+ +

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.

+ +

First of all, add a {{htmlelement("style")}} element to your page, inside your HTML head. It should look like so:

+ +
<style>
+
+</style>
+ +

Inside the style tags, add the following 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;
+}
+ +

Save and reload, and you'll see that your form should look much less ugly.

+ +
+

Note: You can find our version on GitHub at first-form-styled.html (also see it live).

+
+ +

Sending form data to your web server

+ +

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 action and method attributes.

+ +

We provide a name 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.

+ +

To name the data in a form you need to use the name attribute on each form widget that will collect a specific piece of data. Let's look at some of our form code again:

+ +
<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>
+
+  ...
+
+ +

In our example, the form will send 3 pieces of data named "user_name", "user_email", and "user_message". That data will be sent to the URL "/my-handling-form-page" using the HTTP POST method.

+ +

On the server side, the script at the URL "/my-handling-form-page" 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 Sending form data article later on.

+ +

Summary

+ +

Congratulations, you've built your first web form. It looks like this live:

+ +

{{ EmbedLiveSample('A_simple_form', '100%', '240', '', 'Learn/Forms/Your_first_form/Example') }}

+ +

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.

+ +

{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}

+ +

In this module

+ + + +

Advanced Topics

+ + diff --git a/files/my/learn/html/forms/html5_input_types/index.html b/files/my/learn/html/forms/html5_input_types/index.html deleted file mode 100644 index 74b3202f26..0000000000 --- a/files/my/learn/html/forms/html5_input_types/index.html +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: The HTML5 input types -slug: Learn/HTML/Forms/HTML5_input_types -translation_of: Learn/Forms/HTML5_input_types ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}
- -

In the previous article we looked at the {{htmlelement("input")}} element, covering the original values of the type attribute available since the early days of HTML. Now we'll look at the functionality of newer form controls in detail, including some new input types, which were added in HTML5 to allow collection of specific types of data.

- - - - - - - - - - - - -
Prerequisites:Basic computer literacy, and a basic understanding of HTML.
Objective:To understand the newer input type values available to create native form controls, and how to implement them using HTML.
- -
-

Note: Most of the features discussed in this article have wide support across browsers. We'll note any exceptions. If you want more detail on browser support, you should consult our HTML forms element reference, and in particular our extensive <input> types reference.

-
- -

Because HTML form control appearance may be quite different from a designer's specifications, web developers sometimes build their own custom form controls. We cover this in an advanced tutorial — How to build custom form widgets.

- -

E-mail address field

- -

This type of field is set using the value email for the {{htmlattrxref("type","input")}} attribute:

- -
<input type="email" id="email" name="email">
- -

When this {{htmlattrxref("type","input")}} is used, the user is required to type a valid email address into the field. Any other content causes the browser to display an error when the form is submitted. You can see this in action in the below screenshot.

- -

An invalid email input showing the message "Please enter an email address."

- -

You can also use the multiple attribute in combination with the email input type to allow several email addresses to be entered in the same input (separated by commas):

- -
<input type="email" id="email" name="email" multiple>
- -

On some devices — notably, touch devices with dynamic keyboards like smart phones — a different virtual keypad might be presented that is more suitable for entering email addresses, including the @ key. See the Firefox for Android keyboard screenshot below for an example:

- -

firefox for android email keyboard, with ampersand displayed by default.

- -
-

Note: You can find examples of the basic text input types at basic input examples (see the source code also).

-
- -

This is another good reason for using these newer input types — improving the user experience for users of these devices.

- -

Client-side validation

- -

As you can see above, email, along with other newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. It is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server.

- -

But it should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because client-side validation is too easy to turn off, so malicious users can still easily send bad data through to your server. Read Website security for an idea of what could happen; implementing server-side validation is somewhat beyond the scope of this module, but you should bear it in mind.

- -

Note that a@b is a valid email address according to the default provided constraints. This is because the email input type allows intranet email addresses by default. To implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the Client-side form validation article later on.

- -
-

Note: If the data entered is not an email address, the {{cssxref(':invalid')}} pseudo-class will match, and the {{domxref('validityState.typeMismatch')}} property will return true.

-
- -

Search field

- -

Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value search for the {{htmlattrxref("type","input")}} attribute:

- -
<input type="search" id="search" name="search">
- -

The main difference between a text field and a search field is how the browser styles its appearance.  Often, search fields are rendered with rounded corners; they also sometimes display an "Ⓧ", which clears the field of any value when clicked). Additionally, on devices with dynamic keyboards, the keyboard's enter key may read "search", or display a magnifying glass icon.

- -

The below screenshots show a non-empty search field in Firefox 71, Safari 13, and Chrome 79 on macOS, and Edge 18 and Chrome 79 on Windows 10. Note the clear icon only appears if the field has a value, and, apart from Safari, it is only displayed when the field is focused.

- -

Screenshots of search fields on several platforms.

- -

Another feature worth noting is that the values of a search field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website. This tends to happen automatically in most modern browsers.

- -

Phone number field

- -

A special field for filling in phone numbers can be created using tel as the value of the {{htmlattrxref("type","input")}} attribute:

- -
<input type="tel" id="tel" name="tel">
- -

When accessed via a touch device with a dynamic keyboard, most devices will display a numeric keypad when type="tel" is encountered, meaning this type is useful whenever a numeric keypad is useful, and doesn't just have to be used for telephone numbers.

- -

The following Firefox for Android keyboard screenshot provides an example:

- -

firefox for android email keyboard, with ampersand displayed by default.

- -

Due to the wide variety of phone number formats around the world, this type of field does not enforce any constraints on the value entered by a user. (This means it may include letters, etc.).

- -

As we mentioned earlier, The pattern attribute can be used to enforce constraints, which you'll learn about in Client-side form validation.

- -

URL field

- -

A special type of field for entering URLs can be created using the value url for the {{htmlattrxref("type","input")}} attribute:

- -
<input type="url" id="url" name="url">
- -

It adds special validation constraints to the field. The browser will report an error if no protocol (such as http:) is entered, or if the URL is otherwise malformed. On devices with dynamic keyboards, the default keyboard will often display some or all of the colon, period, and forward slash as default keys.

- -

See below for an example (taken on Fireox for Android):

- -

firefox for android email keyboard, with ampersand displayed by default.

- -
Note: Just because the URL is well-formed doesn't necessarily mean that it refers to a location that actually exists!
- -

Numeric field

- -

Controls for entering numbers can be created with an {{HTMLElement("input")}} {{htmlattrxref("type","input")}} of number. This control looks like a text field but allows only floating-point numbers, and usually provides buttons in the form of a spinner to increase and decrease the value of the control. On devices with dynamic keyboards, the numeric keyboard is generally displayed.

- -

The following screenshot (from Firefox for Android) provides an example:

- -

firefox for android email keyboard, with ampersand displayed by default.

- -

With the number input type, you can constrain the minimum and maximum values allowed by setting the {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} attributes.

- -

You can also use the step attribute to set the increment increase and decrease caused by pressing the spinner buttons. By default, the number input type only validates if the number is an integer. To allow float numbers, specify step="any". If omitted, the step value defaults to 1, meaning only whole numbers are valid.

- -

Let's look at some examples. The first one below creates a number control whose value is restricted to any value between 1 and 10, and whose increase and decrease buttons change its value by 2.

- -
<input type="number" name="age" id="age" min="1" max="10" step="2">
- -

The second one creates a number control whose value is restricted to any value between 0 and 1 inclusive, and whose increase and decrease buttons change its value by 0.01.

- -
<input type="number" name="change" id="pennies" min="0" max="1" step="0.01">
- -

The number input type makes sense when the range of valid values is limited, for example a person's age or height. If the range is too large for incremental increases to make sense (such as USA ZIP codes, which range from 00001 to 99999), the tel type might be a better option; it provides the numeric keypad while forgoing the number's spinner UI feature.

- -
-

Note: number inputs are not supported in versions of Internet Explorer below 10.

-
- -

Slider controls

- -

Another way to pick a number is to use a slider. You see these quite often on sites like housebuying sites where you want to set a maximum property price to filter by. Let's look at a live example to illustrate this:

- -

{{EmbedGHLiveSample("learning-area/html/forms/range-example/index.html", '100%', 200)}}

- -

Usage-wise, sliders are less accurate than text fields. Therefore, they are used to pick a number whose precise value is not necessarily important.

- -

A slider is created using the {{HTMLElement("input")}} with its {{htmlattrxref("type","input")}} attribute set to the value range. The slider-thumb can be moved via mouse or touch, or with the arrows of the keypad.

- -

It's important to properly configure your slider. To that end, it's highly recommended that you set the min, max, and step attributes which set the minimum, maximum and increment values, respectively.

- -

Let's look at the code behind the above example, so you can see how its done. First of all, the basic HTML:

- -
<label for="price">Choose a maximum house price: </label>
-<input type="range" name="price" id="price" min="50000" max="500000" step="100" value="250000">
-<output class="price-output" for="price"></output>
- -

This example creates a slider whose value may range between 50000 and 500000, which increments/decrements by 100 at a time. We've given it default value of 250000, using the value attribute.

- -

One problem with sliders is that they don't offer any kind of visual feedback as to what the current value is. This is why we've included an {{htmlelement("output")}} element — to contain the current value (we'll also look at this element in the next article). You could display an input value or the output of a calculation inside any element, but <output> is special — like <label>, it can take a for attribute that allows you to associate it with the element or elements that the output value came from.

- -

To actually display the current value, and update it as it changed, you must use JavaScript, but this is relatively easy to do:

- -
const price = document.querySelector('#price')
-const output = document.querySelector('.price-output')
-
-output.textContent = price.value
-
-price.addEventListener('input', function() {
-  output.textContent = price.value
-});
- -

Here we store references to the range input and the output in two variables. Then we immediately set the output's textContent to the current value of the input. Finally, an event listener is set to ensure that whenever the range slider is moved, the output's textContent is updated to the new value.

- -
-

Note: range inputs are not supported in versions of Internet Explorer below 10.

-
- -

Date and time pickers

- -

Gathering date and time values has traditionally been a nightmare for web developers. For good user experience, it is important to provide a calendar selection UI, enabling users to select dates without necessating context switching to a native calendar application or potentially entering them in differing formats that are hard to parse. The last minute of the previous millenium can be expressed in the following different ways, for example: 1999/12/31, 23:59 or 12/31/99T11:59PM.

- -

HTML date controls are available to handle this specific kind of data, providing calendar widgets and making the data uniform.

- -

A date and time control is created using the {{HTMLElement("input")}} element and an appropriate value for the {{htmlattrxref("type","input")}} attribute, depending on whether you wish to collect dates, times, or both. Here's a live example that falls back to {{htmlelement("select")}} elements in non-supporting browsers:

- -

{{EmbedGHLiveSample("learning-area/html/forms/datetime-local-picker-fallback/index.html", '100%', 200)}}

- -

Let's look at the different available types in brief. Note that the usage of these types is quite complex, especially considering browser support (see below); to find out the full details, follow the links below to the reference pages for each type, including detailed examples.

- -

datetime-local

- -

<input type="datetime-local"> creates a widget to display and pick a date with time with no specific time zone information.

- -
<input type="datetime-local" name="datetime" id="datetime">
- -

month

- -

<input type="month"> creates a widget to display and pick a month with a year.

- -
<input type="month" name="month" id="month">
- -

time

- -

<input type="time"> creates a widget to display and pick a time value. While time may display in 12-hour format, the value returned is in 24-hour format.

- -
<input type="time" name="time" id="time">
- -

week

- -

<input type="week"> creates a widget to display and pick a week number and its year.

- -

Weeks start on Monday and run to Sunday. Additionally, the first week 1 of each year contains the first Thursday of that year—which may not include the first day of the year, or may include the last few days of the previous year.

- -
<input type="week" name="week" id="week">
- -

Constraining date/time values

- -

All date and time controls can be constrained using the min and max attributes, with further constraining possible via the step attribute (whose value is given in seconds).

- -
<label for="myDate">When are you available this summer?</label>
-<input type="date" name="myDate" min="2013-06-01" max="2013-08-31" step="3600" id="myDate">
- -

Browser support for date/time inputs

- -

You should be warned that the date and time widgets don't have the best browser support. At the moment, Chrome, Edge, and Opera support them well, but there is no support in Internet Explorer, Safari has some mobile support (but no desktop support), and Firefox supports time and date only.

- -

The reference pages linked to above provide suggestions on how to program fallbacks for non-supporting browsers; another option is to consider using a JavaScript library to provide a date picker. Most modern frameworks have good components available to provide this functionality, and there are standalone libraries available to (see Top date picker javascript plugins and libraries for some suggestions).

- -

Color picker control

- -

Colors are always a bit difficult to handle. There are many ways to express them: RGB values (decimal or hexadecimal), HSL values, keywords, etc.

- -

A color control can be created using the {{HTMLElement("input")}} element with its {{htmlattrxref("type","input")}} attribute set to the value color:

- -
<input type="color" name="color" id="color">
- -

When supported, clicking a color control will tend to display the operating system's default color picking functionality for you to actually make your choice with. The following screenshot taken on Firefox for macOS provides an example:

- -

firefox for android email keyboard, with ampersand displayed by default.

- -

And here is a live example for you to try out:

- -

{{EmbedGHLiveSample("learning-area/html/forms/color-example/index.html", '100%', 200)}}

- -

The value returned is always a lowercase 6-value hexidecimal color.

- -
-

Note: color inputs are not supported in Internet Explorer.

-
- -

Summary

- -

That brings us to the end of our tour of the HTML5 form input types. There are a few other control types that cannot be easily grouped together due to their very specific behaviors, but which are still essential to know about. We cover those in the next article.

- -

{{PreviousMenuNext("Learn/Forms/Basic_native_form_controls", "Learn/Forms/Other_form_controls", "Learn/Forms")}}

- -

In this module

- - - -

Advanced Topics

- - diff --git a/files/my/learn/html/forms/index.html b/files/my/learn/html/forms/index.html deleted file mode 100644 index 215164d6a6..0000000000 --- a/files/my/learn/html/forms/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: HTML forms -slug: Learn/HTML/Forms -tags: - - Beginner - - Featured - - Forms - - Guide - - HTML - - Landing - - Learn - - NeedsTranslation - - TopicStub - - Web -translation_of: Learn/Forms ---- -
{{LearnSidebar}}
- -

This module provides a series of articles that will help you master HTML forms. HTML forms are a very powerful tool for interacting with users; however, for historical and technical reasons, it's not always obvious how to use them to their full potential. In this guide, we'll cover all aspects of HTML forms, from structure to styling, from data handling to custom widgets.

- -

Prerequisites

- -

Before starting this module, you should at least work through our Introduction to HTML. At this point you should find the {{anch("Basic guides")}} easy to understand, and also be able to make use of our Native form widgets guide.

- -

The rest of the module however is a bit more advanced — it is easy to put form widgets on a page, but you can't actually do much with them without using some advanced form features, CSS, and JavaScript. Therefore, before you look at the other sections we'd recommend that you go away and learn some CSS and JavaScript first.

- -
-

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Basic guides

- -
-
Your first HTML form
-
The first article in our series provides your very first experience of creating an HTML form, including designing a simple form, implementing it using the right HTML elements, adding some very simple styling via CSS, and how data is sent to a server.
-
How to structure an HTML form
-
With the basics out of the way, we now look in more detail at the elements used to provide structure and meaning to the different parts of a form.
-
- -

What form widgets are available?

- -
-
The native form widgets
-
We now look at the functionality of the different form widgets in detail, looking at what options are available to collect different types of data.
-
- -

Validating and submitting form data

- -
-
Sending form data
-
This article looks at what happens when a user submits a form — where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated with sending form data.
-
Form data validation
-
Sending data is not enough — we also need to make sure that the data users fill out in forms is in the correct format we need to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and don't get frustrated when trying to use our apps. Form validation helps us achieve these goals — this article tells you what you need to know.
-
- -

Advanced guides

- -
-
How to build custom form widgets
-
You'll come across some cases where the native form widgets just don't provide what you need, e.g. because of styling or functionality. In such cases, you may need to build your own form widget out of raw HTML. This article explains how you'd do this and the considerations you need to be aware of when doing so, with a practical case study.
-
Sending forms through JavaScript
-
This article looks at ways to use a form to assemble an HTTP request and send it via custom JavaScript, rather than standard form submission. It also looks at why you'd want to do this, and the implications of doing so. (See also Using FormData objects.)
-
HTML forms in legacy browsers
-
Article covering feature detection, etc. This should be redirected to the cross browser testing module, as the same stuff is covered better there.
-
- -

Form styling guides

- -
-
Styling HTML forms
-
This article provides an introduction to styling forms with CSS, including all the basics you might need to know for basic styling tasks.
-
Advanced styling for HTML forms
-
Here we look at some more advanced form styling techniques that need to be used when trying to deal with some of the more difficult-to-style elements.
-
Property compatibility table for form widgets
-
This last article provides a handy reference allowing you to look up what CSS properties are compatible with what form elements.
-
- -

See also

- - diff --git a/files/my/learn/html/forms/your_first_form/index.html b/files/my/learn/html/forms/your_first_form/index.html deleted file mode 100644 index 03f72249e9..0000000000 --- a/files/my/learn/html/forms/your_first_form/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: ပထမဆုံး Form -slug: Learn/HTML/Forms/Your_first_form -translation_of: Learn/Forms/Your_first_form ---- -
{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
- -

Web form တစ်ခုဖန်တီးဖို့အတွက် ပထမဆုံးအတွေ့အကြုံကို ဆောင်းပါးစီးရီးရဲ့ ပထမဦးဆုံးသော ဒီဆောင်းပါးမှာ ရရှိမှာပါ။,  HTML form controls တွေနဲ့ အခြား HTML elements တွေကိုမှန်ကန်စွာအသုံးချပြီး ရိုးရိုး form တစ်ခုကို ဒီဇိုင်းပုံဖော်ခြင်းနဲ့ လက်တွေ့ရေးဆွဲရပါမယ်။ CSS ကိုသုံးပြီး အဲဒီ Form ကို ရိုးရိုးလေး အလှဆင်တာနည်းနည်းလုပ်ရမယ်။ ဆာဗာကို ဒေတာတွေဘယ်လိုပို့သလဲဆိုတာလည်း လေ့လာရပါမယ်။ အပေါ်မှာပြောခဲ့တာတွေ တစ်ခုချင်းစီကို နောက်ပိုင်းမှာ နည်းနည်းပိုပြီးအသေးစိတ်ရှင်းပြပေးသွားပါမယ်။

- - - - - - - - - - - - -
Prerequisites:Basic computer literacy, and a basic understanding of HTML.
Objective:To gain familiarity with what web forms are, what they are used for, how to think about designing them, and the basic HTML elements you'll need for simple cases.
- -

What are web forms?

- -

Web forms 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 Sending form data 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).

- -

A web form's HTML is made up of one or more form controls (sometimes called widgets), plus some additional elements to help structure the overall form — they are often referred to as HTML forms. 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.

- -

Form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users.

- -

Designing your form

- -

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.

- -

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:

- - - -

In this article, we'll build a simple contact form. Let's make a rough sketch.

- -

The form to build, roughly sketch

- -

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.

- -

Active learning: Implementing our form HTML

- -

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")}}.

- -

Before you go any further, make a local copy of our simple HTML template — you'll enter your form HTML into here.

- -

The {{HTMLelement("form")}} element

- -

All forms start with a {{HTMLelement("form")}} element, like this:

- -
<form action="/my-handling-form-page" method="post">
-
-</form>
- -

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 action and method attributes:

- - - -
-

Note: We'll look at how those attributes work in our Sending form data article later on.

-
- -

For now, add the above {{htmlelement("form")}} element into your HTML {{htmlelement("body")}}.

- -

The {{HTMLelement("label")}}, {{HTMLelement("input")}}, and {{HTMLelement("textarea")}} elements

- -

Our contact form is not complex: the data entry portion contains three text fields, each with a corresponding {{HTMLelement("label")}}:

- - - -

In terms of HTML code we need something like the following to implement these form widgets:

- -
<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>
- </ul>
-</form>
- -

Update your form code to look like the above.

- -

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 for attribute on all {{HTMLelement("label")}} elements, which takes as its value the id of the form control with which it is associated — this is how you associate a form control with its label.

- -

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 How to structure a web form.

- -

On the {{HTMLelement("input")}} element, the most important attribute is the type 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 Basic native form controls article later on.

- - - -

Last but not least, note the syntax of <input> vs. <textarea></textarea>. This is one of the oddities of HTML. The <input> 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 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 value attribute like this:

- -
<input type="text" value="by default this element is filled with this text">
- -

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:

- -
<textarea>
-by default this element is filled with this text
-</textarea>
- -

The {{HTMLelement("button")}} element

- -

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 </ul> tag:

- -
<li class="button">
-  <button type="submit">Send your message</button>
-</li>
- -

The {{htmlelement("button")}} element also accepts a type attribute — this accepts one of three values: submit, reset, or button.

- - - -
-

Note: You can also use the {{HTMLElement("input")}} element with the corresponding type to produce a button, for example <input type="submit">. 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.

-
- -

Basic form styling

- -

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.

- -
-

Note: If you don't think you've got the HTML code right, try comparing it with our finished example — see first-form.html (also see it live).

-
- -

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.

- -

First of all, add a {{htmlelement("style")}} element to your page, inside your HTML head. It should look like so:

- -
<style>
-
-</style>
- -

Inside the style tags, add the following 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;
-}
- -

Save and reload, and you'll see that your form should look much less ugly.

- -
-

Note: You can find our version on GitHub at first-form-styled.html (also see it live).

-
- -

Sending form data to your web server

- -

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 action and method attributes.

- -

We provide a name 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.

- -

To name the data in a form you need to use the name attribute on each form widget that will collect a specific piece of data. Let's look at some of our form code again:

- -
<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>
-
-  ...
-
- -

In our example, the form will send 3 pieces of data named "user_name", "user_email", and "user_message". That data will be sent to the URL "/my-handling-form-page" using the HTTP POST method.

- -

On the server side, the script at the URL "/my-handling-form-page" 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 Sending form data article later on.

- -

Summary

- -

Congratulations, you've built your first web form. It looks like this live:

- -

{{ EmbedLiveSample('A_simple_form', '100%', '240', '', 'Learn/Forms/Your_first_form/Example') }}

- -

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.

- -

{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}

- -

In this module

- - - -

Advanced Topics

- - -- cgit v1.2.3-54-g00ecf From f2d1345f562368f653d8b98ebeb8027aa57f42d3 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:48:38 +0100 Subject: unslug my: modify --- files/my/_redirects.txt | 3 ++ files/my/_wikihistory.json | 36 +++++++++++------------ files/my/learn/forms/html5_input_types/index.html | 3 +- files/my/learn/forms/index.html | 3 +- files/my/learn/forms/your_first_form/index.html | 3 +- 5 files changed, 27 insertions(+), 21 deletions(-) diff --git a/files/my/_redirects.txt b/files/my/_redirects.txt index 2b7b852379..2cffca4f69 100644 --- a/files/my/_redirects.txt +++ b/files/my/_redirects.txt @@ -1,3 +1,6 @@ # FROM-URL TO-URL /my/docs/Learn/CSS/CSS-မိတ်ဆက် /en-US/docs/Learn/CSS/First_steps +/my/docs/Learn/HTML/Forms /my/docs/Learn/Forms +/my/docs/Learn/HTML/Forms/HTML5_input_types /my/docs/Learn/Forms/HTML5_input_types +/my/docs/Learn/HTML/Forms/Your_first_form /my/docs/Learn/Forms/Your_first_form /my/docs/Web/Guide/HTML /my/docs/Learn/HTML diff --git a/files/my/_wikihistory.json b/files/my/_wikihistory.json index 61aea2e4ed..b9672c7b5f 100644 --- a/files/my/_wikihistory.json +++ b/files/my/_wikihistory.json @@ -35,24 +35,6 @@ "waizinnaing" ] }, - "Learn/HTML/Forms": { - "modified": "2020-07-16T22:21:00.247Z", - "contributors": [ - "Jeffrey_Yang" - ] - }, - "Learn/HTML/Forms/HTML5_input_types": { - "modified": "2020-07-16T22:22:06.907Z", - "contributors": [ - "wesleydanbury69" - ] - }, - "Learn/HTML/Forms/Your_first_form": { - "modified": "2020-08-24T11:21:29.703Z", - "contributors": [ - "robertaungzinpyae" - ] - }, "Learn/JavaScript": { "modified": "2020-07-16T22:29:42.023Z", "contributors": [ @@ -137,5 +119,23 @@ "contributors": [ "wilsunluk" ] + }, + "Learn/Forms/HTML5_input_types": { + "modified": "2020-07-16T22:22:06.907Z", + "contributors": [ + "wesleydanbury69" + ] + }, + "Learn/Forms": { + "modified": "2020-07-16T22:21:00.247Z", + "contributors": [ + "Jeffrey_Yang" + ] + }, + "Learn/Forms/Your_first_form": { + "modified": "2020-08-24T11:21:29.703Z", + "contributors": [ + "robertaungzinpyae" + ] } } \ No newline at end of file diff --git a/files/my/learn/forms/html5_input_types/index.html b/files/my/learn/forms/html5_input_types/index.html index 74b3202f26..1e3a209b8c 100644 --- a/files/my/learn/forms/html5_input_types/index.html +++ b/files/my/learn/forms/html5_input_types/index.html @@ -1,7 +1,8 @@ --- title: The HTML5 input types -slug: Learn/HTML/Forms/HTML5_input_types +slug: Learn/Forms/HTML5_input_types translation_of: Learn/Forms/HTML5_input_types +original_slug: Learn/HTML/Forms/HTML5_input_types ---
{{LearnSidebar}}
diff --git a/files/my/learn/forms/index.html b/files/my/learn/forms/index.html index 215164d6a6..03f1ed316c 100644 --- a/files/my/learn/forms/index.html +++ b/files/my/learn/forms/index.html @@ -1,6 +1,6 @@ --- title: HTML forms -slug: Learn/HTML/Forms +slug: Learn/Forms tags: - Beginner - Featured @@ -13,6 +13,7 @@ tags: - TopicStub - Web translation_of: Learn/Forms +original_slug: Learn/HTML/Forms ---
{{LearnSidebar}}
diff --git a/files/my/learn/forms/your_first_form/index.html b/files/my/learn/forms/your_first_form/index.html index 03f72249e9..ec562f30b2 100644 --- a/files/my/learn/forms/your_first_form/index.html +++ b/files/my/learn/forms/your_first_form/index.html @@ -1,7 +1,8 @@ --- title: ပထမဆုံး Form -slug: Learn/HTML/Forms/Your_first_form +slug: Learn/Forms/Your_first_form translation_of: Learn/Forms/Your_first_form +original_slug: Learn/HTML/Forms/Your_first_form ---
{{LearnSidebar}}{{NextMenu("Learn/Forms/How_to_structure_a_web_form", "Learn/Forms")}}
-- cgit v1.2.3-54-g00ecf