How to set up smartphones and PCs. Informational portal
  • home
  • Advice
  • Values ​​from and to in html form. HTML Forms

Values ​​from and to in html form. HTML Forms

More than once we have seen Web pages where we were asked to enter some data in the input fields. HTML has a mechanism for getting data from the user. Naturally, this data still needs to be processed, but this is done by specialized programs. Let's look at how they interact with Web pages.

So, the user has uploaded a Web page for himself, which contains the controls for entering information. They are all combined into a common set called form. Each form has a button, by clicking on which the data entered by the user is transferred to the processing program. This program is hosted on a Web server that serves this page. Such programs can be created using a wide variety of programming technologies. What unites them is only a single order of receiving data from a Web page. Data is transferred using the Common Gateway Interface (CGI). Therefore, processing programs are often referred to as CGI applications or CGI scripts.

So, the application receives data and processes it. Then it can either send an e-mail, or perform some operation in the database, or send the user a new Web page, the possible actions are limited only by the properties of the technology and the imagination of the programmer. With the help of such programs, all kinds of registration systems, feedback systems, guest books, forums, chats operate. With their help, more branched and complex systems are created, for example, online stores.

In order to create such applications, you still need to be able to program and know the appropriate rules for creating CGI applications. As long as we do not know how to do this, we still have to use publicly available CGI scripts. But if we get these applications, then the user input form must still be done independently. In this section, we will learn how to do this.

Form delimited by tags

and
... Between these tags are tags that create input controls and tags for creating normal Web page content, that is, the input controls themselves can be located in a table, which in turn is completely placed in the form. Tag
does not create any displayable structure. Rather, it is intended for internal grouping of objects.

Tag , of course, has a number of parameters that set the properties of the created form. Let's consider these parameters.

  • Parameter action is required. Its value is a URL indicating the location of the CGI application that will process the data entered by the user using the control of this form.
  • Parameter method is intended to indicate the way in which data will be transferred to the processing application. One of two predefined key words is used as a parameter value: get or post... Now we do not need to find out which mechanisms are implemented using this or that method. However, the accompanying documentation for the CGI application specifies which data transfer method should be used. The default icon is get.
  • Parameter enctype used to specify the type of data to be submitted from the form. There is usually no need to use it, since the value application / x-www-form-urlencoded The default is ideal for the vast majority of CGI applications.
  • Parameter accept-charset is used in cases when the user transfers from the form to the application not only information, but also files. In this case, we can explicitly specify the encoding of the transferred files. As the value of this parameter, a text string is used, in which one or several encoding names are written. In the event that several encodings are used, their names are separated by spaces or commas. The default is unknown, which tells the server that it should figure out the encodings used by itself
  • Parameter accept specifies the types of files to be transferred. Usually not used, since the server is quite capable of recognizing the type of the received file itself.
  • Parameter name allows you to specify a unique name for the form. Naturally, one Web page can contain several forms. In this case, the values ​​of the name parameters should not be the same.

Tag with its covering twin , in fact, create a container for placing information input organs. Most of these inputs are implemented using the tag ... Let's demonstrate this with a small example (Fig. 1.32).

Listing 1.33

"http://www.w3.org/TR/html4/strict.dtd">



<р>Field for entering a line of text< input type="text">




Rice. 1.32. Browser window showing the result of displaying the file shown in Listing 1.33

So, in the illustration you can see that we were able to create a text input field and a button, upon clicking on which the information entered by the user will be sent to the CGI application for processing. And if we look at the listing code, we will see that both the button and the input field were created using the same tag ... Adjusting the properties of this tag is done using its many parameters, which we will now consider.

  • Parameter type is perhaps the key parameter. Using its value, we can set the type of the created control. One of the following keywords is used as the value: text, password, checkbox, radio, submit, reset, file, hidden, image, button. The default is text. We'll look at these types in more detail a little later.
  • Parameter name designed to set unique names for each control. Although this parameter is optional, it is highly recommended that you use it. The accompanying documentation for CGI applications must indicate how the names should be with the relevant input authorities.
  • Parameter value used to specify the default value displayed for buttons and text input fields. If we use switches, then the parameter value value will not be visible to the user, but it is this value that the CGI processing application will get if the user selects the appropriate radio button.
  • Parameter cheked used only for check boxes and radio buttons. It sets their initial state. If this parameter will be entered in the tag<input>, then the switch will be turned on. The parameter is used without values.
  • Parameter disabled makes the control unavailable for user use. The parameter is used without values.
  • Parameter readonly applies only to input organs of text password types. Using this parameter means that the data displayed in these fields cannot be changed.
  • Parameter size usually specifies the size of the data entry body. But for each separate type of input organs, its action is specific.
  • Parameter maxiength allows you to set the maximum possible number of characters that the user can enter in the text input fields. The parameter value is a positive integer.
  • Parameter src used in cases where we create graphics-related input bodies. The value of this parameter is the URL of the graphic file that contains the displayed image.
  • Parameter alt allows you to create short descriptions of the created data entry body. This description can be displayed as a small hint-tooltip when the user hovers over the given input organ.
  • Parameter tabindex sets the number of the control in the sequence of all objects, moving the input focus between which is carried out by successive presses of the tabulation key.
  • Parameter accesskey allows you to set a "hot key", when pressed by the user, the input focus will go to this control.

So, we looked at the parameters used in the tag ... But we already know that with this tag we can create a variety of form objects. It's time to deal with them in detail.

The objects included in the form are divided into two types - data entry organs and buttons that initiate various actions. First, let's see how we can create input organs.

One of the most common form objects is the single line input field. We saw in Listing 1.33 that it is created using the type parameter with the value text. At the same time, quite often we need to set limits on the maximum possible number of characters that the user can enter in this field. This limitation is implemented using the maxlength parameter.

There is a modification of the one-line text input field, which is designed specifically for entering secret information, for example, passwords. They display the entered text and replace it with asterisks. Such input fields are created using the following construction:

Using type checkbox allows you to create independent switches. They are all familiar squares, in which with a click of the mouse we can set and uncheck the checkboxes. This uses the value parameter. The value of this parameter will be passed to the CGI processing application if the user checks this check box.

We can also create groups of radio buttons, which are often called dependent radio buttons. In this group, the user can select and check only one radio button. Each radio button is created with a tag with parameter type, assigned the value radio. For the browser to understand that several radio buttons belong to the same group, their values ​​for the name parameter must be the same. But at the same time, the values ​​of the value parameters must be different for them.

Let's take an example of the rules for creating and displaying the considered information input bodies.

Listing 1.34

:! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 // EN"
http: //www.w3.Qrg/TR/html4/strict.dtd ">
, </head><br> <form action="http://www.mysite.com/.cgi-bin/test.exe" method="post"> <br> <р>Field for entering a line of text <input type="text"> </p> <br> <р>Password field <input type="password"> </p><br> <р>Independent switch <input type="checkbox" value="checked"> </p><br> <р>Switch group</р><br> <р>Alternative 1 <input type="radio" name="groupl" value="checkl"> </p><br> <р>Alternative 2 <input type»"^adio" name="groupl" value="checki checked></p> <br><p>(! LANG: Alternative 3 <input type=!}"radio" name="groupl" value="check3"> </p><br> <input type="submit" value="send"> </form> <br> </body> </html> </i></p><p>In the above illustration (Fig. 1.33), you can see how the entered text is displayed in the usual input field and in the confidential information input field. And Listing 1.34 clearly shows how we can create check boxes and radio button groups. At the same time, we initially set the default cocked state to the second switch in the group. But the user, of course, can always choose the required alternative himself.</p><p>Using the parameter <i>type</i> with the assigned value hidden we can create hidden fields. This field not only prevents the user from entering any information, but it is not displayed at all in the viewport. This type of field is usually used for official purposes of developers. And using the value <i>file</i> we can create a file name input field. In this case, next to the text input field, a button with the name Browse is automatically created, when you click on it, a standard file selection dialog opens.</p><p>In addition to information input bodies, we can also place controls. In this case, They are buttons. Forms use three kinds of buttons. The submit button submits user input to the rendering CGI application. The "reset" button removes the information entered by the user from the input organs and displays the information set by default. There are also simple buttons, the reaction of which we can program ourselves using scripting languages. Also, instead of the "submit" button, we can use any graphic image. Let's look at ways to create these controls.</p> <p><img src='https://i2.wp.com/tepka.ru/html4b/33.jpg' height="478" width="427" loading=lazy loading=lazy></p> <p>Rice. 1.33. <i>Browser window with the result of displaying the file shown in the listing. 1.34</i></p> <p>A "submit" button is created using the following structure:</p> <p><i><input type="submit" vа1uе="Подтвердить"> </i></p> <p>As you can see, the button is created using the parameter <i>type</i>, a inscription on it is specified by the value of the parameter <i>value</i>... If we need to create a button to clear information input fields, we can apply the following code snippet:</p> <p><i> <input type="reset" value="Clear"> </i></p><p>And for a simple button, we use the following construction:</p> <p><i> <input type-"button" value="Button"> </i></p><p>We have already said that instead of the usual "submit" button, we can use any graphic image. To do this, we use the following code snippet:</p> <p><i> <input type="invage" src="http://www.mysite.com/image/pict.gif"> </i></p><p>In this case, there is no need to use the parameter <i>value</i>, since you do not need to set the label on the button. But then it is necessary to use the parameter <i>src</i> whose value is the URL of the graphic file to use.</p><p>But in addition to the organs for entering information that we have already examined, there are additional organs that are not implemented using the tag <i><input> </i>... These include a drop-down list box and a multi-line text input field.</p><p>The drop-down list is implemented using the tag <i><select> </i>... In this case, naturally, its closing pair is also used <i> </select>. </i> Between these tags, we declare list items using tags <i><option>. </i> Tag <i><select> </i> naturally has some properties that are controlled by parameters.</p> <ul><li>Parameter <i>name</i>, as usual, specifies a unique name for the given input field, that is, the drop-down list.</li> <li>Parameter <i>size</i> sets the number of lines visible when expanding the list. Naturally, there may be more items in the list than the displayed rows. But in this case, only a vertical scroll bar will be displayed. The parameter value is a positive integer.</li> <li>Parameter <i>multiple</i> it is used if we want to allow the user to select several values ​​from a list at once.</li> <li>Parameter <i>disable</i> forces the browser to display the given dropdown list, but the user will not be able to activate it and select any value.</li> <li>Parameter <i>tabindex</i>, as we already know, sets the ordinal number of the data input element in the sequence of objects, the transition of the input focus between which is made using the tabulation key.</li> </ul><p>A drop-down list items themselves are created using tags <option>... These tags also have their own properties. But there are not so many of them.</p> <ul><li>Parameter <i>selected</i> is used for those items that will be highlighted by default when the drop-down list is activated.</li> <li>Parameter <i>value</i> specifies the value that will be passed to the CGI rendering application if the user selects this particular item from the dropdown list.</li> </ul><p>Now let's look at a simple procedure for creating drop-down lists in HTML-document forms (Fig. 1.34).</p> <p>Listing 1.35</p> <p><i><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"<br>"http://www.w3.org/TR/htm!4/Strict.dtd"> <br> <html><br> <head><title>






/ html>

Rice. 1.34. Browser window showing the result of displaying the file shown in Listing 1.35

There is only one data entry element left to consider. This is a multi-line text input field. It is implemented using the tag textareax This tag creates an input area that can be quite large, and is usually used for entering medium to large amounts of text information. A tag cannot do without parameters. And we will definitely consider them.

  • Parameter name allows you to set a unique name for a given data entry element,
  • Parameter rows sets the number of lines to display for the created input field. In fact, this is its height, but it is set in lines. This parameter is required. A positive integer is used as the value.
  • Parameter cols specifies the width, in characters, of the generated text input field. The parameter is also required.
  • Parameter disabled used if the field needs to be made unavailable for use.
  • Parameter readonly used to create fields with non-editable text. The text in such input fields can only be displayed, but the user cannot change it.
  • Parameter tabindex sets the ordinal number of the data input element in the sequence of objects, the transition of the input focus between which is made using the tabulation key.
  • Parameter accesskey allows you to set a key, when pressed, the input focus will be automatically transferred to this input field.

Now let's see how such input fields are created (Fig. 1.35).

Listing 1.36

"http://www.w3.org/TR/html4/strict.dtd">







In addition to these input fields, there is another object that relates to the creation of forms. We can create so-called text labels for some data entry authorities.

Indeed, in fact, the radio buttons and checkboxes are quite small in size, and to activate them it is undesirable to precisely hit the active area with the mouse. It is not always convenient. Therefore, in many programs with a well-thought-out user interface, you can activate such controls even by clicking on their text names. HTML gives us exactly the same opportunity.

Rice. 1 .35. A browser window showing the result of displaying the file in Listing 1 .36

To create similar text labels and headings associated with specific data entry elements, we can use the tag But we can only bind such labels to those data entry organs for which we have explicitly set the identifying id. It is on it that the correspondence is established between the label and the object of the form. The main parameter for the tag the for parameter is used, the value of which is the value of the id parameter of the object to which the given text label is bound. Let's give an example of creating such a connection. We will first create a check box and then attach an associated text title to it. A similar operation is performed using the following code snippet:


Input type = "checkbox" name = "check" value = "(! LANG: checked" id="checkl"> !}

However, you can do without the for parameter if the tag declaring the associated data entry body is placed between the tags
And this is where we can end our review of the procedure for creating forms for entering data in static HTML documents.

HTML. Forms and their attributes

Form elements are familiar to all users of the modern global network. These are text and password entry fields, standard buttons, radio buttons, checkboxes, drop-down lists, etc. The most obvious uses are: entering keywords in search engines, working with e-mail through a web interface, registering on a website, web profiles, online tests. Immediately, we note that the use of forms implies interactivity and, therefore, providing functionality is inevitably associated with programming (client or server). Perhaps, in most cases, forms are used to transfer data to the server, however, on the client side there are tasks in which it is convenient to use forms (for example, a calendar or calculator).

The role of HTML is to describe the required elements and arrange them on the page. All attributes of forms and their elements, which are described using HTML, are translated into the corresponding properties of DOM objects and used in JavaScript scripting.

The descriptions of the form controls that are designed to provide the necessary functionality should be located in the form container, the attributes of which are essential at the stage of scripting. The main attributes of the form element are:

attribute description possible values
name name
action the address of the server script file that will process the completed and submitted form
method method of transferring data to the server get
post
enctype the content type used to submit the form to the server
multipart / form-data
accept-charset a list of data input character encodings that will be processed by the server
target
onSubmit JavaScript to run before submitting form data to the server
onReset JavaScript to execute when you reset the values ​​of form elements to their default values

After carefully reading the descriptions of the attributes, you will notice that most of them are relevant when processing form data in server-side script. Three attributes have default values ​​(which is generally uncommon in HTML).

All of the above attributes are formally optional, however

  • when working on the client side, you must specify the form name name in order to be able to access form elements from JavaScript;
  • Submitting form data to the server requires at least an action attribute that defines the server-side processing script.

The meaning of at least two attributes needs to be explained in more detail.

Method attribute

The method attribute has two main possible values: get (the default) and post.

The meaning of these values ​​is as follows. When submitting data using the get method, the form data is sent to the server in the request header, and when using the post method, it is sent in the body of the request. The transfer of text data can be done by any of these methods. But binary data can only be sent using the post method. This happens in the case of a non-server file upload (everyone understands an example - an attachment to an email). By the way, in this case you need to specify enctype = ”multipart / form-data” (see the notes on the enctype attribute below).

So, except for the case of transferring binary data, both possible methods can be applied equally. This does not in any way affect the complexity of developing a server script that accepts data from a form. What is the preferred method? It makes sense to take a close look at the resources on the web and make sure that the get method is used in the vast majority of cases (for example, in search engines). Can this be considered an unspoken rule of thumb? To answer this question, you should compare the get and post methods in at least three aspects: the amount of data transferred, security, and user friendliness.

  1. It should be borne in mind that the maximum amount of data transmitted by the get method is limited, depending on the protocol settings, and in any case cannot exceed 8192 KB.
  2. Passing confidential information using the get method certainly poses a certain security risk, since the get string remains in the logs of all intermediate servers and the proxy server.
  3. On the other hand, you can think about which option is more convenient for the user of the information resource.

When passed by the get method, the user has the pleasure of seeing the form data in the address bar. Characters other than the standard Latin alphabet are encoded. For example, space is% 20. Each of us constantly observes this situation when working with search engines. Let's set, for example, in Yandex the keyword combination “ HTML language"And see in the address bar:

Word " language"Is encoded with the sequence% FF% E7% FB% EA, and" HTML "is transmitted as is. Upon receiving such a request, the appropriate server program will access the database and ultimately generate and send a list of search results to the browser. Is it pleasant to look at such an address bar? No. But the user can save a unique bookmark to the generated page.

When submitted using the post method, the form data is also sent to the server. In this case, the user does not see anything "superfluous" in the address bar. But other problems appear: an attempt to refresh the page causes a message that is incomprehensible to most users: "... the page cannot be refreshed without re-sending the data ...". And do not save the bookmark.

Summary. Apparently, in most typical tasks, you should choose the default get method in all cases, except transfers to the server:

  • binary data,
  • confidential information,
  • large amount of data.

Enctype attribute

This attribute has two possible meanings:

  • application / x-www-form-urlencoded(default)
  • multipart / form-data

The first value is used in the vast majority of cases. It makes no sense to specify it explicitly - it is already assumed by default. The second type of encoding (multipart / form-data) is indicated in the only case: when uploading a binary file to the server. In this case, it is necessary to set the method = "post" attribute.

HTML Forms are controls that are used to collect information from website visitors.

Web forms are made up of a collection of text boxes, buttons, lists, and other controls that are clickable. Technically, forms transfer data from a user to a remote server.

To receive and process form data, web programming languages ​​are used, such as PHP, Perl.

Before HTML5, web forms were a collection of multiple elements. , ending with a button ... It took a lot of effort to style the forms in different browsers. In addition, forms required JavaScript to validate input, and were stripped of specific input field types for specifying day-to-day information such as dates, email addresses, and URLs.

HTML5 forms solved most of these common problems by introducing new attributes, providing the ability to change the appearance of form elements by CSS3.

Rice. 1. Improved web forms with HTML5

HTML5 Form Creation

1. Element

Any form is based on an element ...... It does not provide for data entry, as it is a container, holding together all the form controls - fields... The attributes of this element contain information that is common to all form fields, so you need to include logically combined fields in one form.

Table 1. Tag Attributes
Attribute Meaning / Description
accept-charset The attribute value is a space delimited character encoding list to be used to submit the form, for example .
action Required Attribute which specifies the url of the form handler on the server to which the data is passed. It is a file (for example, action.php) that describes what to do with the form data. If the attribute value is not specified, then after page reload the form elements will take their default values.
If all the work will be performed on the client side by JavaScript scripts, then the value # can be specified for the action attribute.
You can also make sure that the form filled out by the visitor arrives in your mail. To do this, you need to make the following entry:
autocomplete

enctype Used to indicate MIME-type of data sent with the form, for example, enctype = "multipart / form-data". Specified only if method = "post".
application / x-www-form-urlencoded is the default content type, indicating that the submitted data is a list of URL-encoded form variables. Space characters (ASCII 32) will be encoded as +, and special characters such as! will be encoded in hex as% 21.
multipart / form-data - used to submit forms containing files, non-ASCII data and binary data, consists of several parts, each of which represents the content of an individual form element.
text / plain - indicates that plain (not html) text is transmitted.
method Specifies how form data is passed.
The get method passes data to the server through the browser address bar. When generating a request to the server, all variables and their values ​​form a sequence like www.anysite.ru/form.php?var1=1&var2=2. Variable names and values ​​are appended to the server address after the? and are separated by the & sign. All special characters and letters other than Latin are encoded in the% nn format, the space is replaced by +. This method should be used if you are not transferring large amounts of information. If you intend to send a file along with the form, this method will not work.
The post method is used to send large amounts of data, as well as confidential information and passwords. The data sent using this method is not visible in the URL header because it is contained in the body of the message.
name Sets form name to be used to access form elements through scripts, for example name = "opros".
novalidate Disables validation on the button for submitting the form. The attribute is used without specifying a value
target Specifies the window to which information will be directed:
_blank - new window
_self - the same frame
_parent - the parent frame (if it exists, if not, then to the current one)
_top is the top-level window in relation to this frame. If the call is not from a child frame, then to the same frame.

2. Grouping form elements

Element

...
is intended for grouping elements related to each other, thus dividing the form into logical fragments.

Each group of elements can be named using the element that follows the tag

... The group name appears on the left in the upper border
... For example, if the element
contact information is stored:

Contact Information


Rice. 2. Grouping form elements using

Table 2. Attributes of the tag
Attribute Meaning / Description
disabled If the attribute is present, then a group of related form elements that are inside the container
disabled for filling and editing. Used to restrict access to some form fields containing previously entered data. The attribute is used without specifying a value -
.
form
in the same document. Indicates one or more shapes to which this group of elements belongs. The attribute is currently not supported by any browser.
name Defines name to be used to reference elements in JavaScript, or to reference form data after the form has been filled out and submitted. Analogous to the id attribute.

3. Create form fields

Element creates most of the form fields. Element attributes differ depending on the type of field that the element is used to create.

Using css styles, you can change the font size, font type, color and other properties of the text, as well as add borders, background color and background image. The width of the field is set by the width property.

Table 3. Tag Attributes
Attribute Meaning / Description
accept Specifies the type of file allowed to be sent to the server. Indicated only for ... Possible values:
file_extension - allows uploading files with the specified extension, for example, accept = ". gif", accept = ". pdf", accept = ". doc"
audio / * - allows downloading audio files
video / * - allows uploading video files
image / * - allows uploading images
media_type - indicates the media type of the uploaded files.
alt Defines alternative text for images, indicated only for .
autocomplete Responsible for memorizing the values ​​entered into the text field and auto-substituting them on subsequent input:
on - means that the field is not protected, and its value can be stored and retrieved,
off - disables autocomplete for form fields.
autofocus Allows you to make sure that in the loaded form this or that input field already has focus (has been selected), being ready to enter a value.
checked The attribute checks if the checkbox is checked by default on page load for fields of type type = "checkbox" and type = "radio".
disabled
form The attribute value must be equal to the id attribute of the element in the same document. Specifies one or more forms to which this form field belongs.
formaction Sets the url of the file that will process the data entered into the fields when the form is submitted. It is set only for fields of type type = "submit" and type = "image". This attribute overrides the value of the action attribute of the form itself.
formenctype Determines how the form field data will be encoded when it is sent to the server. Overrides the value of the enctype attribute of the form. It is set only for fields of type type = "submit" and type = "image". The options are:
application / -x-www-form-urlencoded is the default. All characters are encoded before sending (spaces are replaced with +, special characters are converted to ASCII HEX values)
multipart / form-data - characters are not encoded
text / plain - spaces are replaced with the + character, and special characters are not encoded.
formmethod The attribute specifies the method that the browser will use to submit form data to the server. It is set only for fields of type type = "submit" and type = "image". Overrides the value of the method attribute of the form. The options are:
get is the default. The data from the form (name / value pair) is appended to the url and sent to the server: url? Name = value & name = value
post - Form data is sent as an http request.
formnovalidate Specifies that the form field data should not be validated when the form is submitted. Overrides the value of the novalidate attribute of the form. Can be used without specifying an attribute value.
formtarget Determines where to display the response received after the form has been submitted. It is set only for fields of type type = "submit" and type = "image". Overrides the value of the target attribute of the form.


_parent - Loads the response to the parent frame
_top - loads the response in full screen
framename - Loads the response into a frame with the specified name.
height The attribute value contains the number of pixels without specifying a unit. Sets the height of a form field of type type = "image", for example ... It is recommended to set both the height and the width of the field at the same time.
list Is a reference to an item , contains its id. Allows you to provide the user with several options to choose from when he begins to enter a value in the corresponding field.
max Allows you to limit the allowed numeric data input to the maximum value; the attribute value can contain an integer or fractional number. It is recommended to use this attribute in conjunction with the min attribute. Works with the following field types: number, range, date, datetime, datetime-local, month, time, and week.
maxlength The attribute specifies the maximum number of characters that can be entered in the field. The default is 524288 characters.
min Allows you to restrict valid numeric input to the minimum value.
multiple Allows the user to enter multiple attribute values, separated by a comma. Applies to files and email addresses. Specified without an attribute value.
name Specifies the name that will be used to access the element for example in css stylesheets. Analogous to the id attribute.
pattern Allows you to define using regular expression the syntax of the data that must be allowed in a specific field. For example, pattern = "(3) - (3)" - square brackets set the range of valid characters, in this case - any lowercase letters, the number in curly braces indicates that three lowercase letters are needed, followed by a dash, then three digits in the range from 0 to 9.
placeholder Contains the text that is displayed in the input field before filling (most often it is a hint).
readonly It does not allow the user to change the values ​​of form elements, while selection and copying of text is available. Specified without an attribute value.
required Displays a message stating that this field is required. If the user attempts to submit the form without entering the required value in this field, a warning message will be displayed on the screen. Specified without an attribute value.
size Specifies the apparent width of the margin, in characters. The default is 20. Works with the following field types: text, search, tel, url, email, and password.
src Specifies the url of an image to use as a button for submitting form data. Specified only for the field .
step Used for items that require numeric input, indicates the amount of increase or decrease in values ​​during range adjustment (step).
type button - creates a button.
checkbox - turns the input field into a checkbox that can be checked or cleared, for example
I have a car
color - Generates color pickers in supporting browsers, giving users the ability to select color values ​​in hexadecimal format.
date - allows you to enter a date in the format dd.mm.yyyy.
Birthday:
datetime-local - allows you to enter the date and time, separated by an uppercase English letter T according to the pattern dd.mm.yyyy hh: mm.
Birthday - day and time:
email - browsers that support this attribute will expect the user to enter data that matches the syntax of email addresses.
Email:
file - allows you to upload files from the user's computer.
Select a file:
hidden - Hides a control that is not visible to the browser and prevents the user from changing the default values.
image - creates a button, allowing you to insert an image instead of the text on the button.
month - Allows the user to enter the year and month using the pattern yyyy-mm.
number - intended for entering integer values. Its min, max, and step attributes set the upper, lower, and spacing values, respectively. These attributes are assumed for all items that have numeric values. Their default values ​​depend on the element type.
Indicate the quantity (from 1 to 5):
password - creates text fields in the form, while the characters entered by the user are replaced with asterisks, bullets, or other icons set by the browser.
Enter password:
radio - creates a radio button - a control in the form of a small circle that can be turned on or off.
Vegetarian:
range - will allow you to create an interface element such as a slider, min / max - will allow you to set the selection range
reset - creates a button that clears the form fields from user-entered data.
search - denotes a search field, by default the input field is rectangular.
Search:
submit - Creates a standard clickable button. The button collects information from the form and submits it for processing.
text - Creates text boxes on a form, outputting a one-line text box for entering text.
time - allows you to enter time in 24-hour format using the hh: mm template. In supporting browsers, it appears as a numeric input control with a mouse-clickable value and only accepts time values.
Specify the time:
url - the field is intended for specifying URL addresses.
Main page:
week - The appropriate pointer tool allows the user to select one week of the year, and then provides data entry in nn-yyyy format. Depending on the year, the number of weeks can be 52 or 53.
Indicate the week:
value Specifies the text displayed on a button, in a box, or associated text. Not specified for fields of type file.
width The attribute value contains the number of pixels. Allows you to set the width of the form fields.

4. Text input fields

Element used instead of element when you need to create large text boxes. The text displayed as the original value is placed inside the tag. The dimensions of the field are set using the cols attributes - the horizontal dimensions, rows - the vertical dimensions. The height of the field can be set with the height property. All sizes are calculated based on the size of one monospaced font character.

Table 4. Tag Attributes

7. Buttons

Element creates clickable buttons. Unlike buttons created ( , , , ), inside the element .

Buttons allow users to submit data to a form, clear the content of a form, or take some other action. You can create borders, change the background, and align the text on the button.

Table 9. Tag Attributes
Attribute Meaning / Description
autofocus Sets focus to a button on page load.
disabled Disables the button, making it non-clickable.
form Indicates one or more forms to which this button belongs. The attribute value is the identifier of the corresponding form.
formaction The attribute value contains the url of the handler for the form data sent when the button is clicked. Only for a button of type type = "submit". Overrides the value of the action attribute specified for the element .
formenctype Specifies the type of encoding of the form data before it is submitted to the server when buttons of type type = "submit" are clicked. Overrides the value of the enctype attribute specified for the element ... Possible values:
application / x-www-form-urlencoded is the default. All characters will be encoded before sending.
multipart / form-data - characters are not encoded. Used when files are uploaded using a form.
text / plain - characters are not encoded and spaces are replaced with the + character.
formmethod The attribute defines the method that the browser will use to submit the form. Overrides the value of the method attribute specified on the element ... It is specified only for buttons of type type = "submit". Possible values:
get - data from the form (name / value pair) is added to the url and sent to the server. This method has restrictions on the size of the sent data and is not suitable for sending passwords and confidential information.
post - data from the form is added as an http request. The method is more reliable and safer than get and has no size limit.
formnovalidate The attribute specifies that form data should not be validated upon submission. It is specified only for buttons of type type = "submit".
formtarget The attribute specifies in which window to display the result after submitting the form. It is specified only for buttons of type type = "submit". Overrides the value of the target attribute specified for the element .
_blank - loads the response into a new window / tab
_self - loads the response into the same window (default)
_parent - Loads the response to the parent frame
_top - loads the response in full screen
framename - Loads the response into a frame with the specified name.
name Specifies the name of the button, the attribute value is text. Used to link to form data after the form has been submitted, or to link to a given button (s) in JavaScript.
type Defines the type of the button. Possible values:
button - clickable button
reset - reset button, returns the original value
submit - a button for submitting form data.
value Sets the default value sent when the button is clicked.

8. Checkboxes and radio buttons in forms

Checkboxes in forms are set using the construction and the switch with .

In contrast to radio buttons, several checkboxes can be set in one form. If the checked attribute is specified for the checkboxes, then when the page is loaded, the checkboxes will already be checked on the corresponding form fields.

Element

Tag FORM sets up a form on a web page. The form is intended for the exchange of data between the user and the server. The scope of application of forms is not limited to sending data to the server; using client scripts, you can access any element of the form, modify it and apply it at your discretion.

A document can contain any number of forms, but only one form can be sent to the server at a time. For this reason, form data must be independent of each other.

When the form is submitted to the server, control of the data is transferred to the CGI program specified by the action parameter of the FORM tag. The browser prepares the information in the form of a "name = value" pair, where the name is determined by the name parameter of the INPUT tag, and the value is entered by the user or set in the default form field. If the GET method is used to send data, then the address bar can take the following form.

http: //www..cgi? nick =% C2% E0% ED% FF +% D8% E0% EF% EE% F7% EA% E8% ED & page = 5

The parameters are listed after the question mark after the address of the CGI program and are separated by an ampersand (&) character. Non-Latin characters are converted to hexadecimal (in the form% HH, where HH is the hexadecimal code for the ASCII character value), space is replaced with a plus (+).

Syntax

...

End tag
Required.

Options
action is the address of the CGI program or document that processes the form data.
enctype - The MIME type of the form information.
method - the method of the HTTP protocol.
name - the name of the form.
target - the name of the window or frame where the handler will load the returned result.

Example 1. Using the FORM tag



How do you think the abbreviation "OS" stands for?

Officers

Operating system

Big striped flies


Description of the FORM tag parameters

ACTION parameter

Description
Specifies the handler to which form data is accessed when it is submitted to the server. The handler can be a CGI program or an HTML document that includes server-side scripts (for example, Parser). After the handler takes action on the form data, it returns a new HTML document.

If the action parameter is absent, the current page is reloaded, returning all form elements to their default values.

Syntax

...

Arguments
The value is the full or relative path to the server file (URL).

Default value
No.

Example 2. Adding a Form Processor




...


You can specify an email address as the handler, starting with the mailto keyword. When the form is submitted, the default mail program will be launched. For security reasons, the browser has established that it is impossible to send the information entered in the form invisibly by mail. For correct data interpretation, use the enctype = "text / plain" parameter in the FORM tag.

Example 3. Using an email address




...


ENCTYPE parameter

Description
Sets the MIME type for data sent with the form. Normally, you do not need to set the enctype parameter, the data is well understood on the server side. However, if you are using a field to send a file (INPUT type = file), you must define the enctype parameter as multipart / form-data.

Syntax

...

Arguments
The name of the MIME type, in any case. It is allowed to set several values ​​at once, separating them with commas.

Default value
application / x-www-form-urlencoded

Example 4. Changing data type



...


METHOD parameter

Description
The method informs the server about the purpose of the request. There are two main methods: GET and POST. There are other methods, but they are still little used.

Syntax

...

Arguments
The value for method is case-insensitive and must be specified without quotes. There are two methods - GET and POST.

GET
This method is one of the most common and is designed to obtain the required information and transmit data in the address bar. In this case, name = value pairs are appended to the address after the question mark and separated by an ampersand (& symbol). The convenience of using the GET method lies in the fact that the address with all parameters can be used repeatedly, saving it, for example, in the browser's "Favorites", and also changing the parameter values ​​directly in the address bar.

POST
The POST method sends data to the server in a browser request. This allows more data to be sent than is available for the GET method, since it has a 4K limit. Large amounts of data are used in forums, postal services, database populations, etc.

Default value
GET

Example 5. Form submission method




...


Parameter NAME

Description
Specifies a unique name for the form. Typically, the name of the form is used to access its elements through scripts.

Syntax

...

Arguments
The name is a set of characters, including numbers and letters. JavaScript is case sensitive, so when accessing a form by name through scripts, use the same spelling as for the name parameter.

Default value
No.

Example 6. Using a form name







Имя:



Параметр TARGET

Описание
После того, как обработчик формы получает данные, он возвращает результат в виде HTML-документа. Вы можете определить окно, в которое будет загружаться итоговая веб-страница. Для этого используется параметр target, в качестве его значения используется имя окна или фрейма. Если параметр target не установлен, возвращаемый результат показывается в текущем окне.

Синтаксис

...

Аргументы
В качестве аргумента используется имя окна или фрейма, заданное параметром name. Если установлено несуществующее имя, то будет открыто новое окно. В качестве зарезервированных имен используются следующие.

Blank - загружает страницу в новое окно браузера.
_self - загружает страницу в текущее окно.
_parent - загружает страницу во фрейм-родитель, если фреймов нет, то этот параметр работает как _self.
_top - отменяет все фреймы и загружает страницу в полном окне браузера, если фреймов нет, то этот параметр работает как _self.

Значение по умолчанию
_self

Пример 7. Открытие новой страницы




...


Назначение форм

HTML-формы предназначены для пересылки данных от удаленного пользователя к Web-серверу. С их помощью можно организовать простейший диалог между пользователем и сервером, например, регистрацию пользователя на сервере или выбор нужного документа из представленного списка. Формы поддерживаются всеми популярными браузерами.

Синтаксис формы

В HTML-документе для задания формы используются тэги

, Документ может содержать несколько форм, но они не могут быть вложены одна в другую.

Тэг

имеет параметры action , method и enctype . Отдельные браузеры ( Netscape , Internet Explorer) поддерживают дополнительные параметры, например, class , name , style и др.

В общем виде форма задается следующим образом:

содержание_формы

Параметр action является единственным обязательным. Его значением является URL-адрес CGI -программы, которая будет обрабатывать информацию, извлеченную из данной формы.

Взаимодействие между браузером и web-сервером

Взаимодействие между клиентом-браузером и Web-сервером осуществляется по правилам, заданным протоколом HTTP, и состоит из запросов клиента и ответов сервера. Запрос разбивается на три части. В первой строке запроса содержится HTTP-команда, называемая методом, URL-адрес запрашиваемого файла и номер версии протокола HTTP. Вторая часть - заголовок запроса. Третья часть - тело запроса, собственно данные, посылаемые серверу.

MIME-типы

Одним из первых применений Интернета была электронная почта, ориентированная на пересылку текстовых сообщений. Часто возникает необходимость вместе с текстом переслать данные в нетекстовом формате, например, упакованный zip-файл, рисунок в формате GIF , JPEG и т. д. Для того, чтобы переслать средствами электронной почты такие файлы без искажения, они кодируются в соответствии с некоторым стандартом. Стандарт MIME ( Multipurpose Internet Mail Extensions, многоцелевые расширения электронной почты для Интернета) определяет набор MIME -типов, соответствующих различным типам данных, и правила их пересылки по электронной почте. Для обозначения MIME -типа используется запись вида тип/ подтип , где тип определяет общий тип данных, например, text , image , application (тип application обозначает специфический внутренний формат данных, используемый некоторой программой), а подтип - конкретный формат внутри типа данных, например, application/zip , image/gif , text/html .

MIME -типы нашли применение в Web, где они называются также медиа -типами, для идентификации формата документов, передаваемых по протоколу HTTP. В HTML-форме параметр enctype определяет медиа -тип, который используется для кодирования и пересылки специального типа данных - содержимого формы.

Значением параметра enctype является медиа -тип, определяющий формат кодирования данных при передаче их от браузера к серверу. Браузер кодирует данные, чтобы исключить их искажение в процессе передачи. Возможны два значения этого параметра: (по умолчанию) и multipart/form-data .

Второй метод нужен только в том случае, если к содержимому формы присоединяется локальный файл, выбранный при помощи элемента формы . В остальных случаях следует использовать метод кодирования по умолчанию.

URL-кодирование

Схема кодирования application/x-www-form-urlencoded одинакова для обоих методов пересылки (GET и POST ) и заключается в следующем. Для каждого элемента формы, имеющего имя, заданное параметром name , формируется пара "name=value" , где value - значение элемента, введенное пользователем или назначенное по умолчанию. Если значение отсутствует, соответствующая пара имеет вид "name=" . Для радиокнопок и переключателей используются значения только выбранных элементов. Если элемент выбран, а значение параметра value не определено, по умолчанию используется значение "on" .

Все пары объединяются в строку, в качестве разделителя служит символ "&" . Так как имена и значения представляют собой обычный текст, то они могут содержать символы, недопустимые в составе URL (метод GET пересылает данные как часть URL). Такие символы заменяются последовательностью, состоящей из символа % и их шестнадцатеричного ASCII- кода. Символ пробела может заменяться не только кодом %20 , но и знаком + (плюс). Признак конца строки, встречающийся в поле textarea , заменяется кодом %0D%0A . Такое кодирование называется URL-кодированием .

Методы передачи данных

Закодированная информация пересылается серверу одним из методов GET или POST . Основное отличие заключается в том, как метод передает информацию CGI -программе.

При использовании метода GET данные формы пересылаются в составе URL-запроса, к которому присоединяются после символа "?" в виде совокупности пар

переменная = значение,

разделенных символом "&" . В этом случае первая строка запроса может иметь следующий вид:

GET /cgi-bin/cgi-program.pl?name=Ivan&surname=Ivanov HTTP/1.1

Часть URL после символа "?" называется строкой запроса . Web-сервер, получив запрос, присвоит переменной среды QUERY_STRING значение строки запроса и вызовет CGI -программу, обозначенную в первой части URL до символа "?" .

При использовании метода POST данные формы пересылаются серверу в теле запроса, после чего передаются сервером в CGI -программу через стандартный ввод .

Методы GET и POST имеют свои достоинства и недостатки. Метод GET обеспечивает лучшую производительность при пересылке форм, состоящих из небольшого набора коротких полей. При пересылке большого объема данных следует использовать метод POST , так как браузер или сервер могут накладывать ограничения на размер данных, передаваемых в составе URL, и отбрасывать часть данных, выходящую за границу. Метод POST , к тому же, является более надежным при пересылке конфиденциальной информации .

Поля ввода формы

Форма отображается в окне браузера в виде набора стандартных элементов управления, используемых для заполнения полей формы значениями, которые затем передаются Web-серверу. Значение вводится в поле ввода пользователем или назначается по умолчанию. Для создания полей средствами языка HTML существуют специальные тэги: ,

Это наиболее употребительный тэг, с помощью которого можно генерировать внутри формы поля для ввода строки текста, пароля, имени файла, различные кнопки. Он имеет два обязательных параметра: type и name . Параметр type определяет тип поля: селекторная кнопка, кнопка передачи и др. Параметр name определяет имя, присваиваемое полю. Оно не отображается браузером, а используется в качестве идентификатора значения, передаваемого Web-серверу. Остальные параметры меняются в зависимости от типа поля. Ниже приведено описание типов полей, создаваемых при помощи тэга , и порождаемых ими элементов ввода.

type="text"

Создает элемент для ввода строки текста.

Дополнительные параметры:

  • maxlength="n" - задает максимальное количество символов, разрешенных в текстовом поле. По умолчанию - не ограничено.
  • size="n" - максимальное количество отображаемых символов.
  • value = "начальное_значение" . Первоначальное значение текстового поля.
type="password"

Создает элемент ввода строки текста, отличающийся от предыдущего только тем, что все вводимые символы представляются в виде символа * . Поле password не обеспечивает безопасности введенного текста, так как на сервер он передается в незашифрованном виде.

type="files"

Создает поле для ввода имени локального файла, сопровождаемое кнопкой Browse . Выбранный файл присоединяется к содержимому формы при пересылке на сервер. Имя файла можно ввести непосредственно или выбрать его из диалогового окна. Для корректной передачи присоединенного файла следует установить значения параметров формы равными enctype="multipart/form-data" и method="post" . В противном случае будет передана введенная строка, то есть маршрутное имя файла, а не его содержимое. Дополнительные параметры maxlength и size имеют тот же смысл, что и для элементов типа text и password .

type="checkbox"

Создает поле для установки флажка. Элементы checkbox можно объединить в группу, установив одинаковое значение параметра name .

Дополнительные параметры:

  • value="строка" . Значение, которое будет передано серверу, если данная кнопка выбрана. Если кнопка не выбрана, значение не передается. Обязательный параметр. Если флажки образуют группу, то передаваемым значением является строка разделенных запятыми значений параметра value всех установленных флажков.
  • checked . Если указан параметр checked , элемент является выбранным по умолчанию.
type="radio"

Создает элемент-переключатель, существующий только в составе группы подобных элементов, из которых может быть выбран только один. Все элементы группы должны иметь одинаковое значение параметра name .

Отображается в виде круглой кнопки. Дополнительные параметры:

  • value="строка" . Обязательный параметр, значение которого передается серверу при выборе данной кнопки. Должен иметь уникальное значение для каждого члена группы .
  • checked . Устанавливает элемент выбранным по умолчанию. Один и только один элемент в группе должен иметь этот параметр.
type="submit"

Создает кнопку передачи, нажатие которой вызывает пересылку на сервер всего содержимого формы. По умолчанию отображается в виде прямоугольной кнопки с надписью Submit .

Дополнительный параметр позволяет изменить надпись на кнопке. Параметр name для данного элемента может быть опущен. В этом случае значение кнопки не включается в список параметров формы и не передается на сервер.

Если параметры name и value присутствуют, например,

,

то в список параметров формы, передаваемых на сервер, включается параметр submit_button="ok" . Внутри формы могут существовать несколько кнопок передачи.

type="reset"

Создает кнопку сброса, нажатие которой отменяет все сделанные изменения, восстанавливая значения полей формы на тот момент, когда она была загружена. По умолчанию отображается в виде прямоугольной кнопки с надписью Reset . Надпись можно изменить при помощи дополнительного параметра

value="название_кнопки"

Значение кнопки Reset никогда не пересылается на сервер, поэтому у нее отсутствует параметр name .

type="image"

Создает элемент в виде графического изображения, действующий аналогично кнопке Submit . Дополнительные параметры:

  • src="url_изображения" . Задает URL-адрес файла с графическим изображением элемента.
  • align="тип_выравнивания" . Задает тип выравнивания изображения относительно текущей строки текста.

Если на изображении элемента щелкнуть мышью, то координаты указателя мыши в виде name.x=n&name.y=m включаются браузером в список параметров формы, посылаемых на сервер.

Top related articles