Creation of HTML forms. Storing data on the client side. Example of creating a registration form

I'm on a scholarly spree these days
I will win your trust through my service,
You write me a promissory note,
So that I don't have any doubts about the payment.

Mephistopheles, in Goethe's Faust

Forms were briefly introduced in the previous chapter as a way to transmit user-entered information over HTTP. They were developed on the web before the advent of JavaScript, with the expectation that interaction with the server occurs when moving to another page.

But their elements are part of the DOM, like the rest of the page, and the DOM elements that represent form fields support several properties and events that other elements do not. This makes it possible to view and manipulate input fields from JavaScript programs and add functionality to classic forms or use forms and fields as the basis for building an application.

Fields A web form consists of any number of input fields surrounded by a tag. HTML offers many different fields, from simple on/off checkboxes to drop-down lists and text input fields. This book will not discuss all types of fields in detail, but we will give a short overview of them.

Many types of input fields use a tag. Its type attribute is used to select the style of the field. Here are some common types:

text text field on one line
password is the same as text, but hides input
checkbox switch on/off
radio part of the field with the ability to choose from several options
file allows the user to select a file on their computer

Form fields do not have to appear inside a tag. They can be placed anywhere on the page. Information from such fields cannot be passed to the server (this is only possible for the entire form), but when we make fields that JavaScript processes, we usually do not need to pass information from the fields via submit.

(text)

(password)

(checkbox)

(radio)

(file)

The JavaScript interface for such elements varies depending on the type. We'll look at each of them a little later.

Multi-line text fields have their own tag. The tag must have a closing tag and use the text inside those tags instead of using the value attribute.

one two Three

And the tag is used to create a field that allows the user to select one of the given options.
Pancakes Casserole Ice cream

When the value of a field changes, the “change” event is fired.

Focus Unlike most elements HTML document, form fields can receive keyboard focus. When you click or otherwise select them, they become active, i.e. main receivers of keyboard input.

If the document has a text field, then the text you type will appear in it only if the field has input focus. Other fields respond differently to the keyboard. For example, it tries to move to an option that contains text that the user enters, and also responds to arrow keys by moving the option selection up and down.

You can control focus from JavaScript using the focus and blur methods. The first one moves focus to the DOM element from which it is called, and the second one removes focus. The value of document.activeElement corresponds to the current element receiving focus.

document.querySelector("input").focus(); console.log(document.activeElement.tagName); // → INPUT document.querySelector("input").blur(); console.log(document.activeElement.tagName); // → BODY

Some pages require the user to immediately start working on one of the form fields. At JavaScript help It's possible to give this field focus when the document is loaded, but HTML also has an autofocus attribute that achieves the same result but tells the browser what our intentions are. In this case, the browser can override this behavior in appropriate cases, such as when the user has moved focus elsewhere.

Browsers traditionally allow the user to move focus using the Tab key. We can influence the navigation order through the tabindex attribute. In the example, the document will move focus from the text field to the OK button, instead of going through the help link first.

(help) OK

By default, most types HTML elements don't get focus. But adding a tabindex to an element makes it possible for it to receive focus.

Disabled fields All fields can be disabled with the disabled attribute, which also exists as a property of the DOM object element.

I'm fine, I'm passed out

Disabled fields do not accept focus or change, and unlike active fields, they usually appear gray and faded.

When a program is in the process of processing a click on a button or other element, which may require communication with the server and take a long time, it is a good idea to disable the element until the action is completed. In this case, when the user loses patience and clicks on the element again, the action will not be repeated again.

The entire form When a field is contained within an element, its DOM element will have a form property that refers to the form. The element, in turn, has an elements property containing an array-like collection of fields.

The name attribute of a field specifies how the value of this field will be determined when sent to the server. It can also be used as a property name when accessing the form's elements property, which acts as both an array-like object (accessed by number) and a map (accessed by name).

Name:
Password:
Login var form = document.querySelector("form"); console.log(form.elements.type); // → password console.log(form.elements.password.type); // → password console.log(form.elements.name.form == form); // → true

A button with a type attribute equal to submit submits the form when clicked. Pressing Enter keys inside a form field has the same effect.

Submitting a form typically means that the browser navigates to the page designated in the form's action attribute, using either a GET or a POST request. But before that, the “submit” property is fired. It can be handled in JavaScript, and the handler can prevent the default behavior by calling event preventDefault on the object.

Value: Save var form = document.querySelector("form"); form.addEventListener("submit", function(event) ( console.log("Saving value", form.elements.value.value); event.preventDefault(); ));

Intercepting “submit” events is useful in several cases. We can write code that checks the validity of the entered values ​​and immediately shows an error instead of passing the form data. Or we can disable form submission by default and let the program handle the input itself, for example using XMLHttpRequest to send data to the server without reloading the page.

Text fields Fields with tags and types text and password, as well as tags, have a common interface. Their DOM elements have a value property that contains their current content as a string of text. Setting this property to a value changes the contents of the field.

The selectionStart and selectionEnd text field properties contain information about the position of the cursor and the text selection. When nothing is selected, their value is the same, and is equal to the cursor position. For example, 0 indicates the beginning of the text, 10 indicates that the cursor is at the 10th character. When part of a field is selected, the properties are different meanings, namely the beginning and end of the selected text. You can also enter a value in these fields.

For example, imagine that you are writing an article about Khasekhemwy, but you are having trouble spelling his name correctly. The following code assigns an event handler to the tag that, when F2 is pressed, inserts the string “Khasekhemwy”.

var textarea = document.querySelector("textarea"); textarea.addEventListener("keydown", function(event) ( // The key code for F2 happens to be 113 if (event.keyCode == 113) ( replaceSelection(textarea, "Khasekhemwy"); event.preventDefault(); ) )); function replaceSelection(field, word) ( var from = field.selectionStart, to = field.selectionEnd; field.value = field.value.slice(0, from) + word + field.value.slice(to); // Put the cursor after the word field.selectionStart = field.selectionEnd = from + word.length );

The replaceSelection function replaces the currently selected text with the specified word, and moves the cursor to a position after that word so that you can continue typing.

The “change” event for a text field does not fire every time a single character is entered. It fires after the field loses focus and its value has been changed. To instantly respond to changes in a text field, you need to register an “input” event, which fires every time you enter a character, delete text, or otherwise manipulate the contents of the field.

In the following example, we see a text field and a counter showing the current length of the entered text.

length: 0 var text = document.querySelector("input"); var output = document.querySelector("#length"); text.addEventListener("input", function() ( output.textContent = text.value.length; ));

Checkboxes and radio buttons The checkbox is a simple binary radio button. Its value can be retrieved or changed through the checked property, which contains a Boolean value.

Make the page purple var checkbox = document.querySelector("#purple"); checkbox.addEventListener("change", function() ( document.body.style.background = checkbox.checked ? "mediumpurple" : ""; ));

A tag is used to associate a piece of text with an input field. The for attribute must match the id of the field. Clicking on the label enables the input field, it receives focus and changes the value - if it is a check mark or radio button.

A radio button is similar to a check mark, but it is linked to other radio buttons with the same name, so only one of them can be selected.

Color: Purple Green Blue var buttons = document.getElementsByName("color"); function setColor(event) ( document.body.style.background = event.target.value; ) for (var i = 0; i< buttons.length; i++) buttons[i].addEventListener("change", setColor);

The document.getElementsByName method returns all elements with the given name attribute. The example iterates through them (via a regular for loop, not a forEach, because the collection returned is not a real array) and registers an event handler for each element. Remember that event objects have a target property that refers to the element that fired the event. This is useful for creating event handlers - our handler can be called by different elements, and it must have a way to access the current element that called it.

Select fields Select fields are similar to radio buttons—they also allow you to select from multiple options. But if radio buttons allow us to control the layout of options, then the type of field is determined by the browser.

Select fields have an option that looks more like a list of checkboxes than radio buttons. If the multiple attribute is present, the tag will allow you to select any number of options, rather than just one.

Pancakes Casserole Ice cream

In most browsers, the appearance of the field will be different from a single-choice field, which usually looks like a drop-down menu.

The size attribute of the tag is used to set the number of options that are visible at once - this way you can influence the appearance of the dropout. For example, by assigning size 3, you will see three lines at once, regardless of whether the multiple option is present.

Each tag has a meaning. It can be defined by the value attribute, but if it is not specified, then the value of the tag determines the text located inside the tag... The element's value property reflects the currently selected option. For a field with the ability to select several options, this property is not particularly needed, because it will contain only one of several selected options.

The field tag can be accessed as an array-like object through the options property. Each option has a selected property indicating whether the option is currently selected. The property can also be changed to make the option selected or unselected.

The following example extracts the selected values ​​from the select field and uses them to create a binary number from the bits. Press Ctrl (or Command on a Mac) to select multiple values ​​at once.

0001 0010 0100 1000 = 0 var select = document.querySelector("select"); var output = document.querySelector("#output"); select.addEventListener("change", function() ( var number = 0; for (var i = 0; i< select.options.length; i++) { var option = select.options[i]; if (option.selected) number += Number(option.value); } output.textContent = number; });

File field The file field was originally intended for uploading files from a computer through a form. IN modern browsers they also allow you to read files from JavaScript. The field acts as a guard for files. The script cannot simply grab and open a file from the user's computer, but if the user selects a file in this field, the browser allows the script to begin reading the file.

The file field usually looks like a button labeled something like “Select File,” with information about the selected file next to it.

var input = document.querySelector("input"); input.addEventListener("change", function() ( if (input.files.length > 0) ( var file = input.files; console.log("You chose", file.name); if (file.type) console.log("It has type", file.type);

The element's files property is an array-like object (not a real array) containing a list of selected files. Initially it is empty. The element does not have simple property file because the user can select multiple files at once when the multiple attribute is enabled.

Objects in the files property have the properties name (file name), size (file size in bytes), and type (file type in the sense of media type - text/plain or image/jpeg).

What it doesn't have is a property containing the contents of the file. You have to try hard to get the content. Since reading a file from disk takes a long time, the interface must be asynchronous so that the document does not freeze. You can think of the FileReader constructor as an XMLHttpRequest constructor, but for files.

var input = document.querySelector("input"); input.addEventListener("change", function() ( Array.prototype.forEach.call(input.files, function(file) ( var reader = new FileReader(); reader.addEventListener("load", function() ( console .log("File", file.name, "starts with", reader.result.slice(0, 20)); reader.readAsText(file));

Reading a file occurs by creating a FileReader object, registering a “load” event for it, and calling its readAsText method, passing the file to the volume. When the download is complete, the contents of the file are stored in the result property.

The example uses Array.prototype.forEach to iterate through the array, since in a normal loop it would be inconvenient to receive the necessary file and reader objects from the event handler. The variables would be common to all iterations of the loop.

FileReaders also has an “error” event when reading a file fails. error object will be saved in the error property. If you don't want to bother your head with another inconvenient asynchronous circuit, you can wrap it in a promise (see Chapter 17):

Function readFile(file) ( return new Promise(function(succeed, fail) ( var reader = new FileReader(); reader.addEventListener("load", function() ( succeed(reader.result); )); reader.addEventListener ("error", function() ( fail(reader.error); )); reader.readAsText(file));

Storing data on the client side Simple HTML pages with the addition of JavaScript can be an excellent basis for mini-applications - small support programs, automating daily tasks. By attaching event handlers to form fields, you can do everything from converting Fahrenheit to Celsius to generating passwords from the main password and website name.

When such an application needs to save information between sessions, JavaScript variables cannot be used - their values ​​are thrown away every time the page is closed. You could set up a server, connect it to the Internet, and then the application would store your data there. We'll look at this in Chapter 20. But it adds work and complexity to you. Sometimes it is enough to store data in your browser. But how?

You can store string data so that it survives page reloads - to do this, you need to put it in a localStorage object. It allows string data to be stored under names (which are also strings), as in this example:

LocalStorage.setItem("username", "marijn"); console.log(localStorage.getItem("username")); // → marijn localStorage.removeItem("username");

The variable is stored in localStorage until it is overwritten, deleted using removeItem or the user clearing the local storage.

For sites with different domains– different compartments in this storage. That is, data saved from a website in localStorage can only be read or overwritten by scripts from the same site.

Browsers also limit the amount of data they can store, usually a few megabytes. This limitation, coupled with the fact that scoring hard drives does not bring profit for people, prevents disk space from being eaten up.

The following code implements a simple program for taking notes. It stores notes as an object, associating titles with content. It is encoded in JSON and stored in localStorage. The user can select a note through the field and change its text in. An entry is added by clicking a button.

Notes: new
var list = document.querySelector("#list"); function addToList(name) ( var option = document.createElement("option"); option.textContent = name; list.appendChild(option); ) // Take the list from local storage var notes = JSON.parse(localStorage.getItem( "notes")) || ("what to buy": ""); for (var name in notes) if (notes.hasOwnProperty(name)) addToList(name); function saveToStorage() ( localStorage.setItem("notes", JSON.stringify(notes)); ) var current = document.querySelector("#currentnote"); current.value = notes; list.addEventListener("change", function() ( current.value = notes; )); current.addEventListener("change", function() ( notes = current.value; saveToStorage(); )); function addNote() ( var name = prompt("Note name", ""); if (!name) return; if (!notes.hasOwnProperty(name)) ( notes = ""; addToList(name); saveToStorage() ; ) list.value = name; current.value = notes)

The script initializes the notes variable with the value from localStorage, and if it is not there, with a simple object with one entry “what to buy”. An attempt to read a missing field from localStorage will return null. By passing null to JSON.parse, we will get null back. Therefore, you can use the || operator for the default value. .

When the data in note changes (adds new entry or the current one changes), the saveToStorage function is called to update the stored field. If we expected that we would store thousands of records, it would be too expensive, and we would have to come up with a more complex storage procedure - for example, a separate field for each record.

When the user adds a record, the code must update the text field, even though the field has a “change” handler. This is necessary because the “change” event occurs only when the user changes the value of the field, and not when the script does it.

There is another object similar to localStorage called sessionStorage. The difference between them is that the contents of sessionStorage are forgotten at the end of the session, which for most browsers means the moment of closing.

The HTML summary provides many various types form fields – text, checkboxes, multiple selection, file selection.

You can get the value and manipulate these fields from JavaScript. Upon change they trigger the “change” event, upon keyboard input – “input”, and many more different keyboard events. They help us catch the moment when the user interacts with the input field. Properties like value (for text fields and select) or checked (for checkboxes and radio buttons) are used to read and write the contents of the fields.

When submitting a form, the “submit” event occurs. The JavaScript handler can then call preventDefault on this event to stop the data being transferred. Form elements do not have to be enclosed in tags.

When the user selected a file with hard drive Through the file selection field, the FileReader interface will allow us to access the contents of the file from a JavaScript program.

The localStorage and sessionStorage objects can be used to store information in a way that will survive page reloads. The first one saves the data forever (or until the user specifically deletes it), and the second one – until the browser is closed.

ExercisesJavaScript Workbench Make an interface that allows you to write and execute pieces of JavaScript code.

Make a button next to that, when clicked, the Function constructor from Chapter 10 will wrap the entered text in a function and call it. Convert the function's return value, or any of its errors, into a string and print it after the text field.

return "hi"; Let's go // Your code.

AutoComplete Complete a text field so that when you type text, a list of options appears below it. You have an array possible options, and you need to show those that begin with the entered text. When the user clicks on a suggested option, it changes the contents of the field to that option.

// Builds an array of global variable names, // like "alert", "document", and "scrollTo" var terms = ; for (var name in window) terms.push(name); // Your code.

Conway's Game of Life This is a simple simulation of life on a rectangular grid, each element of which is alive or not. Each generation (game step) the following rules apply:

Every living cell whose number of neighbors is less than two or more than three dies
- every living cell that has two to three neighbors lives until the next move
- every dead cell that has exactly three neighbors comes to life

The neighbors of a cell are all the cells adjacent to it horizontally, vertically and diagonally, 8 in total.

Please note that the rules apply to the entire grid at the same time, and not to each of the cells in turn. That is, the number of neighbors is counted at one moment before next step, and changes occurring in neighboring cells do not affect the new state of the cell.

Implement the game using any suitable structures. Use Math.random to create random initial populations. Display the field as a grid of checkmarks with a “go to next step” button. When the user turns checkboxes on or off, these changes must be taken into account when calculating the next generation.

Next generation // Your code.

JS, or JavaScript, is a scripting language that runs on the client side and does not require a page reload. JavaScript was developed by Netscape in 1995.

You've probably seen on my website in the guest book or on the forum, forms for adding messages with special buttons. And, if you wanted to get the same one, then this article is for you.

JS Basics

JavaScript code is inserted between the tags and

If the code contains functions, then these functions should be placed in tags between the and tags.

If JavaScript code is placed in a separate file with the extension .js, then you can connect such a file to the HTML code by specifying the file name as the src parameter of the tag

Thus, we connected a JavaScript file to the HTML file.

You can use JavaScript, for example, as a handler for certain events. For example, when you click on a control element with the mouse, the OnClick event occurs.

In order for the browser to “understand” that we need to execute a script written in JS, we specify the javascript pseudo-protocol:

The alert(string s) function displays a window with the text s and one “OK” button.

In this example, when you click on the “Show” button, a window will appear with the text “You clicked the button” and one “OK” button.

Forms

You can access form elements through the following construction:

document.|form_name|.|component_name|

For information input elements ( and ), the value property is available to access the entered or unentered information itself.

function AddText (text) ( document.form1.edit1.value=text; )

In this example, after clicking the “Press me” button, the text “This is Edit” will appear in the text input field. You can also add one more parameter to functions of this kind - an object into which you want to write text. For example, we have two input fields text information and two buttons. When we click on the first button, we will write some text into the first input field, and when we click on the second button, we will write some text into the second field. To do this, we do not have to write two functions; it is enough to write one function, indicating in its parameters, in addition to the text that we want to add, the object into which this text needs to be added.

function AddText2 (object, text) ( object.value=text; )

That's all the function needed to change any text in any text input element. Let's store this function in a separate file called addtext.js

And here is the html page:

Well, that’s probably all I wanted to write. If you have any questions, write them to my email address: [email protected]

Good bad

    A function is a piece of reusable code that can be called anywhere in the program. This eliminates the need again and again...

    Sometimes you need to make a text field, radio buttons or checkbox active or inactive. How to do this dynamically without reloading the page? For this you can…

Good day, fans of web development and those who want to create their own website. Before that, all my publications were devoted to the basic elements of the language, ways to create various content objects, their formatting, structuring, etc. Having mastered the previous topics, you can already create a fairly good website. However, it will be incomplete without today’s topic: “Creating forms in html.”

This section of the language is very important. Therefore, pay special attention to studying it, otherwise the web resource you created will not be released into production. Thus, after reading the article, you will learn why you need to use forms, what tags they are used to create, and you will also be able to try out specific examples in practice. Let's get started!

What is a form and how does it function?

A form is one of the most important objects, which is intended for the exchange of information data between the server and the user.

Simply put, if you want to create an online store with the ability to order products on the website, request registration on a web resource and work with accounts, or provide customers feedback with company managers, then you cannot do without forms.

The form is specified using a special element of the html language.

Note that a code document may contain several tag declarations, but only one request can be sent to the server for data processing. That is why information that is entered by the user into the fields provided for this and relates to different forms should not be dependent. Also, it is not allowed to nest forms one within the other.

For those who are impatient and eager to take a quick look at the code representation, I have attached a simple example of using a panel with a text field for a password with a button:

1 2 3 4 5 6 7 8 9 10 11 12 Example

Example

Maybe now it’s not very clear what and how interacts in this small program, however, I guarantee that after reading this entire article, you will be able to create applications that are much more complex.

Sending data to the server side

In order to send the typed (or selected) information in the dialog box, you must use the standard mechanism - the Submit button.

The code for such a method looks like this:

When you run the presented line, a button will appear with the inscription: “Submit”.

Another way to send data to the server side is to press the Enter key within the dialog box.

After confirmation of shipment specified information, it does not immediately arrive on the server. First, it is processed by the browser, resulting in the form “name=value”.

The name is the tag's type attribute parameter, and the value is the data entered by the user. Next, the converted string is passed to the handler, which is most often specified in action attribute element .

The action parameter itself is not required, and in some cases it is not needed at all. For example, if a website page is written with using php or js, then processing occurs on current page and no links needed.

For a better understanding of the whole picture of the functioning of the site, I would like to add that on the server, work with data is already performed using other languages. So, server-side languages considered: Python, php, C-like languages ​​(C#, C, etc.), Java and others.

Now I would like to stop and talk more about the element. If you explain in simple language, then you need to create text fields, radio buttons, various buttons, hidden fields, checkboxes and other objects.

The tag does not have to be paired with , but if you need to process user records or enter them, for example, into a database, then you cannot do without a container.

The main attributes of this language element hypertext markup are:

  • Text – creates a text field;
  • Submit – creates a button for sending data to the server;
  • Image – responsible for a button with a picture;
  • Reset – sets a button to clear the form;
  • Password – sets a text field specifically for passwords;
  • Checkbox – responsible for fields with checkboxes;
  • Radio – responsible for fields with the selection of one element;
  • Button – creates a button;
  • Hidden – used for hidden fields;
  • File – specifies the field responsible for sending files.
Methods of transmitting information

There are 2 ways to transfer user data to the server side: Get and Post. These methods perform the same action, but they differ significantly from each other. Therefore, before mentioning any of them, let's get acquainted with their features.

Post Get
Size of transmitted documents Limited to the server side. Maximum – 4 KB.
How sent information is displayed Available only when viewed through browser extensions or other special software products. Immediately available to everyone.
Using bookmarks There is no way to add to bookmarks, since requests are not repeated (all pages link to one address). Any page with a request can be saved as bookmarks and returned to it later.
Caching Based on the previous paragraph, all requests are on one page. Each page can be cached separately.
Purpose Used to send large files (books, images, videos, etc.), messages, comments. Great for searching for requested values ​​on a web resource or for sending short text messages.

In order to indicate which of the two data transfer methods the browser should use, the element uses the provided method parameter (for example, method="post" ).

Let's look at the second example. Let's create a form in which you need to enter your personal data (first and last name, date of birth) and create a password. Afterwards we send all this to the server using the Post method.

POST method

Enter your personal information!

For example, to enter a date, there are switches for the number of each parameter (day, month and year), as well as a drop-down panel with the calendar itself for convenience.

Creating a Registration Panel

Basic tags and attributes have been covered. That's why it's time to create a full-fledged registration form using css style markup and validating the entered data. Of course, we won’t be able to see the server work with them, but we will provide the design and important details.

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 Registration Register on the site

Name:

Surname:

Email:

Password:

Repeat password:

Registration body ( background-color:#98FB98; background-attachment: fixed; ) form( background-color:#AEEEE; Color: #006400; font-size:15px; ) h4 ( color: red; text-align: center; ) p ( text-align: center; ) input ( Color: #006400; font-size:15px; border: 5px ridge #98FB98; background-color:#fff; ) Registration on the site For subsequent correct operation in our service, please enter truthful data!

Name:

Surname:

Email:

Password:

Repeat password:

I advise you to save this code programs in a document with the .html extension and utf-8 encoding, and open the latter in a browser window. You will see a registration panel in all its glory with fields for entering your first name, last name, e-mail and repeated password. Notice that when you launch the page, the cursor is immediately positioned in the first text field. This technique is achieved through the autofocus attribute.

Start filling out the fields, leaving one unchanged, and click the “Register” button. As you already noticed, the form will not be submitted, since each element< input>the required attribute is specified. It sets the marked fields as mandatory.

Another interesting point is the specification of type="email" , which appeared in . When using this type of field, the entered information is automatically checked for correctness. In case of errors, the form is not sent to the server.

So the publication has come to an end. In it I tried to collect maximum amount important and relevant knowledge regarding forms. I hope it was useful to you! I would be very grateful if you join the ranks of my subscribers and tell your friends about the blog.

Bye bye!

Best regards, Roman Chueshov

Read: 333 times

HTML forms are complex interface elements. They include various functional elements: input fields and lists, tooltips, etc. All form code is contained within the .

Most web form information is conveyed using the . To enter one line of text, the element is used; for multiple lines, the element is used. The element creates a dropdown list.

The element creates labels for form fields. There are two ways to group labels and fields. If the field is inside an element, then the for attribute does not need to be specified.

Last Name Last Name Last Name

Form fields can be divided into logical blocks using the element. Each section can be given a name using the element.

Contact information Name Email
Rice. 1. Grouping form fields

To make the form more understandable to users, text is added to the form fields to provide an example of the input data. This type of text is called wildcard text and is created using the placeholder attribute.

Required fields must also be highlighted. Before HTML5, the asterisk * symbol was used next to the field name. The new specification introduces a special required attribute, which allows you to mark a required field at the markup level. This attribute instructs the browser (assuming it supports HTML5) not to send data after the user clicks submit until the specified fields are completed.

To change the appearance of a text field when receiving focus, use the focus pseudo-class. For example, you can make the background of the current field darker or add colored frame to make it stand out from the rest:

Input:focus ( background: #eaeaea; )

Another useful HTML5 attribute is the autofocus attribute. It allows you to automatically set focus to the desired initial field for elements and (only one element of each form).

Example of creating a registration form

HTML markup

Registration Name Gender male female E-mail Country Select country of residence Russia Ukraine Belarus Send

Note
action="form.php" - link to the form handler file. Create a file in UTF-8 encoding, upload it to the server and replace action="form.php" with the path to the file on your server.


Rice. 2. Appearance default forms

As you can see from the figure, each form element has default browser styles. Let's clear the styles and style the form elements.

Form-wrap ( width: 550px; background: #ffd500; border-radius: 20px; ) .form-wrap *(transition: .1s linear) .profile ( width: 240px; float: left; text-align: center; padding : 30px; ) form ( background: white; float: left; width: calc(100% - 240px); padding: 30px; border-radius: 0 20px 20px 0; color: #7b7b7b; ) .form-wrap:after, form div:after ( content: ""; display: table; clear: both; ) form div ( margin-bottom: 15px; position: relative; ) h1 ( font-size: 24px; font-weight: 400; position: relative ; margin-top: 50px; ) h1:after ( content: "\f138"; font-size: 40px; font-family: FontAwesome; position: absolute; top: 50px; left: 50%; transform: translateX(-50 %); ) /******************* styling of form elements ******************** **/ label, span ( display: block; font-size: 14px; margin-bottom: 8px; ) input, input ( border-width: 0; outline: none; margin: 0; width: 100%; padding: 10px 15px; background: #e6e6e6; ) input:focus, input:focus ( box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); ) .radio label ( position: relative; padding-left: 50px; cursor: pointer; width: 50%; float: left; line-height: 40px; ) .radio input ( position: absolute; opacity: 0; ) .radio -control ( position: absolute; top: 0; left: 0; height: 40px; width: 40px; background: #e6e6e6; border-radius: 50%; text-align: center; ) .male:before ( content: " \f222"; font-family: FontAwesome; font-weight: bold; ) .female:before ( content: "\f221"; font-family: FontAwesome; font-weight: bold; ) .radio label:hover input ~ . radio-control, .radiol input:focus ~ .radio-control ( box-shadow: inset 0 0 0 2px rgba(0,0,0,.2); ) .radio input:checked ~ .radio-control ( color: red; ) select ( width: 100%; cursor: pointer; padding: 10px 15px; outline: 0; border: 0; background: #e6e6e6; color: #7b7b7b; -webkit-appearance: none; /* uncheck webkit -browsers*/ -moz-appearance: none; /*uncheck in Mozilla Firefox*/ ) select::-ms-expand ( display: none; /*uncheck in IE*/ ) .select-arrow ( position: absolute ; top: 38px; right: 15px; width: 0; height: 0; pointer-events: none; /*activate the display of the list when you click on the arrow*/ border-style: solid; border-width: 8px 5px 0 5px; border-color: #7b7b7b transparent transparent transparent; ) button ( padding: 10px 0; border-width: 0; display: block; width: 120px; margin: 25px auto 0; background: #60e6c5; color: white; font-size: 14px; outline: none; text-transform : uppercase; ) /********************** add adaptability to the form ******************** **/ @media (max-width: 600px) ( .form-wrap (margin: 20px auto; max-width: 550px; width:100%;) .profile, form (float: none; width: 100%;) h1 (margin-top: auto; padding-bottom: 50px;) form (border-radius: 0 0 20px 20px;) )

Form.php file

Note
In the $subject variable, specify the text that will be displayed as the title of the letter;
Your_name - here you can specify the name that will be displayed in the “from whom the letter is from” field;
replace your_site_url with the address of the site with the registration form;
replace your_email with your address Email;
$headers .= "Bcc: your_email". "\r\n"; sends bcc to your email address.