4
Attention!
In the text between tags And A valid HTML document must not be set to other HTML elements that have hyperlink capabilities. In the best case, if the browser provides for this, then such HTML elements will simply be ignored. In the worst case, if the browser does not transfer an HTML document with errors, then its behavior is generally difficult to predict.
Specific to customizing the button created by the HTML BUTTON element is the use of the type attribute to specify the type of button: submit (submits the form when clicked), reset (resets the values of form controls when clicked), or button (custom button associated with a script). In addition, the attributes name, title, disabled, tabindex and accesskey are available, the use of which is completely similar to the use of the INPUT element attributes.
You should pay special attention to the value attribute. Using it just to label a button becomes pointless. However, the HTML 4.01 specification states that the value of this attribute is expected to be submitted along with other form data (apparently when a corresponding button is clicked that has a type attribute value of submit, then setting the value attribute is very useful for determining on the server which button clicked by the user).
Menu When creating forms, you can use another fairly convenient control element that allows you to select one or more alternatives from a list - a menu (or list of parameters). This control is added to a form using three HTML elements: SELECT, OPTGROUP and OPTION. Although it is mandatory to use only the first and last of them.
Let's start with the HTML SELECT element - it is a container of menu items, defined using paired tags And and supports the following attributes:
Name – the name of the menu, which is also used as the name of the parameter when submitting the form;
Size – sets the number of lines simultaneously visible to the user;
Multiple – Boolean attribute, allows you to allow the selection of several menu items at the same time;
Disabled – boolean attribute, deactivates the menu;
Title – tooltip text for the menu;
Tabindex – number when moving between controls using tabs.
A menu control can be represented differently by different browsers: as a list, as a drop-down list, as a drop-down menu, and finally. Let's look at how a menu is presented in Internet Explorer. Depending on the value of the size attribute, the menu may look like shown in Fig. 9.5.
Rice. 9.5. Menu appearance
If you use the multiple attribute, Internet Explorer will show the menu as a simple list even if the size value is 1: you cannot select multiple items at once in a drop-down list.
Below is a fragment of the text of the HTML document that creates the two menus shown in Fig. 9.5 (you will agree that setting a menu is similar to setting lists) (example 9.4).
Example 9.4. Two simple menus
Paragraph 1
Point 2
Point 3
Point 4
Point 5
Point 6
Paragraph 1
Point 2
Point 3
Point 4
Point 5
Point 6
In the example text you also see the previously mentioned HTML OPTION element. So, this element is used to set individual menu items. It is specified by paired tags And (closing tag is optional), between which the text of the menu item is placed. Has the following attributes:
Value – text that will be sent with the form when a menu item is selected;
Selected – a Boolean attribute that allows you to select a menu item by default (you should not set one menu for several items unless the multiple attribute is set);
Disabled is a Boolean attribute that prohibits the selection of a menu item (however, in the implementation of menus with lists, as in Internet Explorer, this is quite difficult to do, so the browser developers did not particularly suffer and did not implement this attribute).
Now it remains to consider why the third HTML element is needed - OPTGROUP. So, the OPTGROUP element is used to group menu items. Groups are created by enclosing HTML OPTION elements that define menu items in the same group within paired tags And . Group options can be configured using the following HTML attributes of the OPTGROUP element:
Label – line with a signature for the group;
Disabled – disable selection of menu items belonging to this group (similar to the disabled attribute for the OPTION element).
Below is an example of dividing menu items into groups for two menus (example 9.5).
Example 9.5. Grouping menu items
Clause 1.1
Clause 1.2
Clause 1.3
Clause 2.1
Clause 2.2
Clause 2.3
Clause 1.1
Clause 1.2
Clause 1.3
Clause 2.1
Clause 2.2
Clause 2.3
The menus described in Example 9.5 look like shown in Fig. 9.6.
Rice. 9.6. Appearance of a menu with grouped items
Control labels Some controls, such as buttons, contain labels that help the user determine the purpose of the controls. For other elements such as text fields, checkboxes, and so on, you have to create labels manually, mixing the form control definitions with the text.
There is another way to set labels for controls - using the HTML LABEL element. Setting signatures in this way is no easier, and even more difficult, but it adds capabilities for automatic processing of an HTML document.
So, let's look at how signatures are created using the LABEL element: between paired tags And The label text is placed, and the for attribute of the LABEL element is set to a value that identifies the desired control.
When setting the value of the for attribute, remember to use the value of the id attribute of the desired control. This means that controls need to additionally set id attribute values. An example of creating a signature this way:
Enter password:
In this example, the LABEL element is clearly associated with a password input field. There is another way in which you can associate a label with a control implicitly (without setting the value of the for attribute of the LABEL element). To do this, you need to place the control in the body of the LABEL element. The previous example might look like this:
Enter password:
The text can appear before or after the control definition. In this case, there must be only one control definition in the body of the HTML LABEL element.
9.3. Grouping controls When creating forms, it is possible to make the general purpose of some controls more expressive by additionally enclosing them in a frame as shown in Fig. 9.1. The frame can be signed or left unsigned.
The frame is created using the HTML FIELDSET element. Between paired tags
And definitions of controls belonging to the group are placed. A frame will be drawn around these controls.To create a caption for a frame, you need to define a LEGEND element inside the FIELDSET element. This HTML element is specified using paired tags And , between which the signature text is placed. You can also “play” with caption alignment using the align attribute, but you should be aware that different browsers implement the values of this attribute differently, and some values are not supported at all.
In conclusion, let's look at how the grouping of the form controls shown in Fig. 1 is implemented. 9.1 (example 9.6).
This example is an almost complete page with a form: it's a pity that there is no real CGI application at somesite.com/cgi-bin/proc.exe that can process the form.
A form in an HTML document is implemented by a container tag FORM, in which all control elements are specified - input fields, buttons, etc. If control elements are specified outside the contents of the FORM tag, then they do not create a form, but are used to build a user interface on a web page, that is, to add various buttons, checkboxes, and input fields to it.
Form elements are processed using scripts, but they may not be processed at all.
Form elements are named through their NAME attribute.
Each form element can have a start and end value, which are character strings. The initial values of the elements are not changed, so user-specified values can be reset. The effect of this action is to set all form controls to their original default values.
HTML 4.01 defines the following control types:
Buttons - are specified using the BUTTON and INPUT elements. There are:
»
submit buttons - when you click on them, they send the form to the server;
»
reset buttons - when you press them, the control elements take on their original values;
»
other buttons - buttons for which the default action is not specified when clicked.
Dependent switches (dependent switches) - are specified by the INPUT element and represent on/off switches. If several radio buttons have the same name, they are mutually exclusive. This means that if one of them is set to the “on” position, then all the others are automatically turned to the “off” position. This is precisely the advantage of using them.
Independent switches (switches with independent latching) - are specified by the INPUT element and are “on/off” switches, but unlike dependent switches, independent switches can accept and change their value independently of other switches. Even if the latter have the same name.
Menu - implemented using SELECT, OPTGROUP and OPTION elements. Menus provide the user with a list of possible choices.
Text input is implemented by INPUT elements if one line is entered, and by TEXTAREA elements if several lines are entered. In both cases, the entered text becomes the current value of the control.
File selection - allows you to submit selected files along with the form, implemented by the INPUT HTML element.
Hidden controls - created by the INPUT control.
As you can see, a lot of elements are specified using the generic INPUT tag.
You can find the complete HTML4 specification
FORM tag - form container
As already mentioned, a form in an HTML document is implemented by the FORM container tag. This tag, with its attributes, indicates the address of the script (script) to which the form will be sent, the method of sending and the characteristics of the data contained in the form. The start and end FORM tags define the boundaries of the form, so specifying them is mandatory.
Here are the attributes of the FORM tag:
action is the only required attribute. Its value is the URL of the requested script that will process the data contained in the form. It is acceptable to use the mailto:URL entry, which will cause the form to be sent by email. If the ACTION attribute is still not specified, then the form content will be sent to the URL from which the web page was loaded;
method - defines the HTTP method used to send form data from the browser to the server. The METHOD attribute can take two values: GET and POST;
enctype is an optional attribute. Specifies the form content type used to determine the encoding format when submitting it. HTML defines two possible values for the ENCTYPE attributes:
APPLICATION/X-WWW-FORM-URLENCODED (default);
MULTIPART/FORM-DATA.
The INPUT tag and its methods
The INPUT element is the most commonly used HTML form tag. This tag implements the main functions of the form. It allows you to create text strings, file names, passwords, etc. inside the form input fields.
Pay attention to the peculiarity of INPUT - it does not have an end tag. The attributes and usage of INPUT depend on how it is used. Let's consider these methods.
» Single-line input fields
The most commonly used input fields are - after all, even a button is an information input field. Let's start with the text information input field. The INPUT tag format for creating a text string input field is:
This tag creates a text field with a maximum allowed text length of maxlen and a size of size familiarity. If the value attribute is specified, the field will initially display the value of this attribute. Optional attributes are marked in square brackets.
Here's an example of a one-line input field:
» Password fields
Of course, the username can be entered using a regular text field. But the password should not be displayed on the screen when you enter it. The password entry field will help us with this:
The principle of operation of this tag is exactly the same as that of a text tag. The difference is that the information entered into the field is not displayed, but is replaced by " asterisks ". It is not recommended to set the default value for security reasons (value ).
Here is an example of a password input field:
» Hidden text field
Hidden fields are used to transmit service information (which the user should not even be aware of). These fields can be used, for example, to transfer settings.
Such fields are sent to the server, but are not displayed on the web page.
» Independent switches
Very often, the user filling out a form in the browser needs to be given the opportunity to specify their preferences by selecting certain values. In this case, these values themselves are given, and next to them a small square field is placed in which you can check or uncheck. In this case, the value, accordingly, will either be selected or not.
You can implement this again using the INPUT tag. To do this, you just need to specify chechbox as the value of the type attribute.
If the switch was enabled at the time the send data button was clicked, then the parameter name=value will be passed to the script. If the checkbox is turned off, then nothing will be passed to the script at all - as if there was no switch at all.
The default switch is either on or off. For a radio button to be enabled by default, it must have a checked attribute.
A checkbox is called independent because its state does not depend on the state of other checkboxes. Thus, several radio buttons can be selected simultaneously on one form.
Here is an example of independent switches:
There is also a switch in HTML that depends on other switches; it is discussed below.
» Dependent switches
A dependent switch, like an independent switch, can be either on or off. In this case, the radio switch is a dependent switch, since there can only be one enabled radio switch on the form. More precisely, if a form contains several radio buttons of the same name, then only one of them can be enabled. When you select one radio button, all radio buttons of the same name are automatically turned off. The value of the name attribute is taken as the name of the switches. There can only be one active switch. Example of listing a form with radio buttons:
This form will look like this:
The first radio button (set to yes ) is enabled by default (we set the checked attribute).
Once the user clicks the Submit button, script.php will be passed the answer parameter (the name attribute of both radio buttons) with the value yes or no (depending on which option the user selected).
And this is what the script text looks like, receiving data from the considered form and processing the response.
» Form submit button
Another INPUT type control is buttons. The submit button is used to send the parameters entered into the form to the script. The syntax of the INPUT tag is as follows:
The value attribute specifies the text that will be written on the submit button. The name attribute specifies the name of the button and is optional. If the value of this attribute is not specified, then the values entered into the form will be passed to the script and that’s it. If the name attribute is specified for the button, then in addition to the main form data, the name=value pair from the button itself will be sent.
» Reset button
In addition to the submit button, there is also a reset button, which resets the form parameters, or rather, sets all form elements to default values. It is advisable for the form to have such a button, especially if it is a large form. The presence of this button ensures that the form is cleared, for example, in the case when incorrect parameters were entered. Reset button syntax:
» Submit button with a picture
Instead of a submit button, you can use a picture to submit data. Clicking this image does the same thing as clicking the submit button. However, in addition to this, the script will be given the coordinates of the click location in the picture. The coordinates will be transmitted in the format name.x=coor_X, y=coor_Y. The syntax for a submit button with a picture is:
Multiline text fields. Tag TEXTAREA
In HTML, multiline text fields are created using the TEXTAREA tag. The field created by this tag allows you to enter and send not just one line, but several lines at once. TEXTAREA tag syntax:
Several meanings regarding the use of attributes: it is still advisable to specify the optional parameters cols and rows. The first one specifies the number of characters per line, and the second specifies the number of lines in the area. The wrap attribute determines the type of text wrapping and how the text in the input field will look:
Virtual - a scroll bar is displayed to the right of the text field. The text you enter appears to be split into lines, and a newline character is inserted when you press a key. ENTER ;
Physical - this type depends on the browser type and looks different;
None - the text appears in the field as the user enters it. If the text does not shrink to one line, a horizontal scroll bar appears.
It should be noted that the most convenient type is Virtual. Here is an example of a multiline text field using the wrap=Virtual attribute.
Purpose of forms HTML forms are designed to send data from a remote user to a Web server. With their help, you can organize a simple dialogue between the user and the server, for example, registering the user on the server or selecting the desired document from the presented list. Forms are supported by all popular browsers.
Form syntax An HTML document uses tags to define a form.
,A document can contain multiple forms, but they cannot be nested ,one inside the other.Tag
The action parameter is the only required one. Its value is the URL of the CGI program that will process the information extracted from this form.
Interaction between browser and web server The interaction between the browser client and the Web server is carried out according to the rules specified by the HTTP protocol and consists of client requests and server responses. The request is divided into three parts. The first line of the request contains an HTTP command called a method, the URL of the requested file, and the HTTP protocol version number. The second part is the request header. The third part is the body of the request, the actual data sent to the server.
MIME types One of the first uses of the Internet was email, which focused on sending text messages. Often there is a need to send data in a non-text format along with text, for example, a packed zip file, a picture in GIF, JPEG format, etc. In order to send such files by email without distortion, they are encoded in accordance with some standard . The MIME standard (Multipurpose Internet Mail Extensions) defines a set of MIME types corresponding to different types of data and rules for sending them via email. To denote a MIME type, a type/subtype notation is used, where type defines a general data type, for example, text, image, application (the application type denotes a specific internal data format used by some program), and subtype defines a specific format within a data type, for example , application/zip , image/gif , text/html .
MIME types are used on the Web, where they are also called media types, to identify the format of documents transmitted over the HTTP protocol. In an HTML form, the enctype parameter specifies the media type that is used for encoding and forwarding special data type - form contents.
The value of the enctype parameter is the media type, which determines the format for encoding data when transmitting it from the browser to the server. The browser encodes the data to prevent it from being corrupted during transmission. There are two possible values for this parameter: (default) and multipart/form-data .
The second method is only needed if a local file selected using a form element is attached to the form content . Otherwise, the default encoding method should be used.
URL encoding Coding scheme application/x-www-form-urlencoded is the same for both transfer methods (GET and POST) and is as follows. For each form element that has a name specified by the name parameter, a pair "name=value" is formed, where value is the value of the element entered by the user or assigned by default. If there is no value, the corresponding pair is "name=" . For radio buttons and radio buttons, only the values of the selected items are used. If an element is selected and the value parameter is undefined, the default value is "on" .
All pairs are combined into a string, using the "&" character as a separator. Because names and values are plain text, they may contain characters that are not allowed as part of a URL (the GET method sends data as part of a URL). Such characters are replaced by a sequence consisting of the % character and their hexadecimal ASCII code. The space character can be replaced not only by the code %20, but also by the + (plus) sign. Line terminator found in a field textarea , is replaced by the code %0D%0A . This encoding is called URL encoding.
Data transfer methods The encoded information is sent to the server using one of the GET or POST methods. The main difference is how the method passes information to the CGI program.
When using the GET method, the form data is sent as part of a URL request, which is appended after the "?" as a set of pairs
variable = value,
separated by "&" character. In this case, the first line of the query might look like this:
GET /cgi-bin/cgi-program.pl?name=Ivan&surname=Ivanov HTTP/1.1
The part of the URL after the "?" called a query string. The web server, upon receiving the request, will assign environment variable QUERY_STRING value of the query string and will call the CGI program indicated in the first part of the URL before the "?" .
When using the POST method, form data is sent to the server in the body of the request, after which it is transferred by the server to the CGI program via standard input .
The GET and POST methods have their advantages and disadvantages. The GET method provides better performance when submitting forms that consist of a small set of short fields. When sending a large amount of data, you should use the POST method, because the browser or server may impose a limit on the size of the data sent as part of the URL and discard some of the data that goes out of bounds. The POST method is also more reliable when sending confidential information .
Form input fields The form is displayed in the browser window as a set of standard controls used to fill the form fields with values, which are then passed to the Web server. The value is entered into the input field by the user or assigned by default. To create fields using HTML, there are special tags:
,
, < textarea > , which are used only inside a tag
Tag
This is the most common tag with which you can generate fields inside the form for entering a line of text, a password, a file name, and various buttons. It has two required parameters: type and name. The type parameter specifies the type of field: selector button, transfer button, etc. The name parameter specifies the name assigned to the field. It is not displayed by the browser, but is used as an identifier for the value passed to the Web server. Other parameters vary depending on the field type. Below is a description of the types of fields created using the tag , and the input elements they generate.
type="text" Creates an element for entering a string of text.
Extra options:
maxlength="n" - sets the maximum number of characters allowed in the text field. By default - unlimited.
size="n" - maximum number of characters displayed.
value = "initial_value"
!} . The initial value of the text field.
type="password" Creates a text string input element that differs from the previous one only in that all characters entered are represented as a * character. The password field does not ensure the security of the entered text, since it is transmitted to the server in unencrypted form.
type="files" Creates a field for entering a local file name, accompanied by a Browse button. The selected file is appended to the form content when sent to the server. You can enter the file name directly or select it from the dialog box. To correctly transfer the attached file, you should set the form parameters to enctype="multipart/form-data" and method="post" . Otherwise, the entered string will be transmitted, that is, the route name of the file, and not its contents. The additional parameters maxlength and size have the same meaning as for elements of type text and password .
type="checkbox" Creates a field for checking a checkbox. Elements checkbox can be combined into a group by setting the name parameter to the same value.
Extra options:
value="string"
. Значение, которое будет передано серверу, если данная кнопка выбрана. Если кнопка не выбрана, значение не передается. Обязательный параметр. Если флажки образуют группу, то передаваемым значением является строка разделенных запятыми значений параметра value
всех установленных флажков.!}
checked. If checked is specified, the element is selected by default.
type="radio" Creates a radio button element that exists only as part of a group of similar elements, of which only one can be selected. All elements of the group must have the same value for the name parameter.
Appears as a round button. Extra options:
value="string"
. Обязательный параметр, значение которого передается серверу при выборе данной кнопки. Должен иметь уникальное значение для каждого члена группы
.!}
checked. Sets the element to be selected by default. One and only one element in a group must have this option.
type="submit" Creates a submit button that, when clicked, causes the entire form content to be sent to the server. By default, it appears as a rectangular button labeled Submit.
An additional parameter allows you to change the label on the button. The name parameter for this element can be omitted. In this case, the button value is not included in the list of form parameters and is not sent to the server.
If the name and value parameters are present, for example,
,
then the submit_button="ok" parameter is included in the list of form parameters passed to the server. Multiple submit buttons can exist within a form.
type="reset" Creates a reset button, which, when clicked, cancels all changes made, restoring the form field values to the moment it was loaded. By default, it appears as a rectangular button labeled Reset. The inscription can be changed using an additional parameter
value="button_name"!}
The Reset button's value is never sent to the server, so it does not have a name parameter.
type="image" Creates a graphical element that functions similarly to a Submit button. Extra options:
src="url_images" . Specifies the URL to the file containing the graphic image of the element.
align="align_type" . Specifies the alignment type of the image relative to the current line of text.
If you click on the element's image, the coordinates of the mouse pointer in the form name.x=n&name.y=m are included by the browser in the list of form parameters sent to the server.
HTML. Forms and their attributes
Form elements are familiar to all users of the modern global network. These are text and password input fields, standard buttons, radio buttons, checkboxes, drop-down lists, etc. The most obvious use cases: entering keywords in search engines, working with email via a web interface, registering on a website, web questionnaires, online tests. Let us immediately 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 the use of forms is convenient (for example, a calendar or calculator).
The role of HTML is to describe the necessary elements and arrange them on the page. All attributes of forms and their elements described using HTML are translated into the corresponding properties of DOM objects and used when creating JavaScript scripts.
Descriptions of form control elements designed to provide the necessary functionality should be located in the form container, the attributes of which are essential at the script development stage. Basic attributes of the form element:
attribute
description
possible values
name
Name
action
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
list of data input character encodings that will be processed by the server
target
onSubmit
JavaScript script that runs before the form data is submitted to the server
onReset
JavaScript script executed when form element values are reset to default values
Having carefully read the attribute descriptions, we note that most of them are relevant when processing form data by a server script. Three attributes have default values (which is generally uncharacteristic of HTML).
All of the above attributes are formally optional, however
when working on the client side, you must set the form name name to be able to access form elements from a JavaScript script;
Sending form data to the server requires, at a minimum, specifying the action attribute, which 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 (default) and post.
The meaning of these meanings is as follows. When sending 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. Transmission of text data can be done using any of these methods. But binary data can only be sent using the post method. This happens when a file is not downloaded from the server (a clear example is an attachment to an email). By the way, in this case you need to specify enctype=”multipart/form-data” (see below for notes on the enctype attribute).
So, with the exception of the case of transferring binary data, both possible methods can be used equally. This does not in any way affect the complexity of developing a server script that accepts form data. Which method is preferable? It makes sense to carefully review the resources available on the Internet and make sure that the get method is used in the vast majority of cases (for example, in search engines). Is this 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.
Please note that the maximum amount of data transferred by the get method is limited, depending on the protocol settings, and in any case cannot exceed 8192 KB.
Transmitting sensitive information using the get method undoubtedly poses a certain security risk, since the get string remains in the logs of all intermediate servers and the proxy server.
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 standard Latin are encoded. For example, the code %20 corresponds to a space. Each of us constantly observes this situation when working with search engines. Let’s set, for example, in Yandex the key phrase “ 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 corresponding server program will access the database and ultimately generate and send a list of search results to the browser. Is it nice to look at such an address bar? No. But the user can save a unique bookmark to the generated page.
When submitting using the post method, the form data is also sent to the server. In this case, the user does not see anything “extra” in the address bar. But other problems appear: an attempt to refresh the page causes a message that is unintelligible to most users: “... updating the page is impossible without resending the data...”. And you can’t save the bookmark.
Summary. It appears that for most typical tasks you should choose the default get method in all cases. except transmission to the server:
binary data,
confidential information,
large volume of data.
enctype attribute
This attribute has two possible values:
application/x-www-form-urlencoded (default)
multipart/form-data
The first value is used in the vast majority of cases. There is no point in specifying it explicitly - it is already assumed by default. The second type of encoding (multipart/form-data) is specified in the only case: when uploading a binary file to the server. In this case, it is necessary to set the method=”post” attribute.
Did you like the article? Share with friends: