Front end learning notes - form

form

1. Make basic forms

Making a basic form requires three elements: form, input, and button elements.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <input name="fave"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

1.1. Definition form

The form elements are summarized as follows:

elementform
Element typeStream element
Allowed parent elementsAny element that can contain stream elements. However, a form element cannot be a descendant of other form elements
Local attributeaction, method, enctype, name, accept charset, novavalidate, target and autocomplete
contentStream content (but mainly label element and input element)
Label usageStart label and end label
Customary styleform { display: block; margin-top: 0em; }

The second key element is input, which is used to collect data entered by users.

elementinput
Element typephrase element
Allowed parent elementsAny element that can contain a phrase element.
Local attributename, disabled, form, type, and other attributes that depend on the value of the type attribute
contentnothing
Label usageVirtual element form
Customary styleNone. The appearance of this form depends on the type attribute

The most important element is button. Users need a way to tell the browser that all data has been entered and it's time to send them to the server. This is mostly done with the button element.

elementbutton
Element typephrase element
Allowed parent elementsAny element that can contain a phrase element.
Local attributename, disabled, form, type, and other attributes that depend on the value of the type attribute
contentphrase element
Label usageStart label and end label
Customary stylenothing

1.2. Viewing form data

Accept data sent by browser:

var http = require('http');
var querystring = require('querystring');

http.createServer(function (req, res) {
  switch(req.url) {
    case '/form':
        if (req.method == 'POST') {
         console.log("[200] " + req.method + " to " + req.url);
         var fullBody = '';
         req.on('data', function(chunk) {
           fullBody += chunk.toString();
         });
         req.on('end', function() {
           res.writeHead(200, "OK", {'Content-Type': 'text/html'});  
           res.write('<html><head><title>Post data</title></head><body>');
           res.write('<style>th, td {text-align:left; padding:5px; color:black}\n');
           res.write('th {background-color:grey; color:white; min-width:10em}\n');
           res.write('td {background-color:lightgrey}\n');
           res.write('caption {font-weight:bold}</style>');
           res.write('<table border="1"><caption>Form Data</caption>');
           res.write('<tr><th>Name</th><th>Value</th>');
           var dBody = querystring.parse(fullBody);
           for (var prop in dBody) {
            res.write("<tr><td>" + prop + "</td><td>" + dBody[prop] + "</td></tr>");
           }
           res.write('</table></body></html>');
           res.end();
         });
       } else {
         console.log("[405] " + req.method + " to " + req.url);
         res.writeHead(405, "Method not supported", {'Content-Type': 'text/html'});
         res.end('<html><head><title>405 - Method not supported</title></head><body>' +
                 '<h1>Method not supported.</h1></body></html>');
       }
      break;
    default:
      res.writeHead(404, "Not found", {'Content-Type': 'text/html'});
      res.end('<html><head><title>404 - Not found</title></head><body>' +
              '<h1>Not found.</h1></body></html>');
      console.log("[404] " + req.method + " to " + req.url);
  };
}).listen(8080);

This script summarizes the data sent by the browser and returns a simple HTML document, which displays those data in the form of HTML tables. It's listening

Port 80, and only process the form data sent by the browser to the URL / form with HTTP POST method.

2. Configuration form

2.1. Configure the action attribute of the form

The action attribute indicates where the browser should send the data collected from the user when submitting the form. If the action attribute is not set, the browser will send the form data to the URL where the HTML document is loaded. If a relative URL is specified for the action attribute, the value will be grafted on the URL of the current page.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
        <base href="http://titan:8080"/>
    </head>
    <body>
        <form method="post" action="/form">
            <input name="fave"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

2.2. Configure HTTP method attributes

The method attribute specifies the HTTP method used to send the form data to the server. The allowed values are get and post, which correspond to the get and post methods of HTTP respectively. The default value used when the method property is not set is get.

GET requests are used for secure interaction. The same request can be initiated any number of times without additional effects. POST request is used for unsafe interaction. The behavior of submitting data will lead to some state changes. The latter approach is mostly used for Web applications.

In general, GET requests should be used to obtain read-only information, while POST requests should be used for various operations that will change the state of the application.

2.3. Configuration data coding

The enctype attribute specifies how the browser encodes the data sent to the server. There are three values available:

valueexplain
application/x-www-form-urlencodedDefault encoding method. It cannot be used to upload files to the server
multipart/form-dataThis encoding method is used to upload files to the server
text/plainThe encoding method varies from browser to browser

In order to understand the working mechanism of these coding methods, you need to add another input element to the form.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <input name="fave"/>
            <input name="name"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

The second input element is added to collect two items of data from the user. The new input element is used to get the user's name. As can be seen from the code, the value of the name attribute of the element is set to name. In the experiment, the enctype attribute of the form will be set to each coding method, and the data entered each time is the same. The first is Apples and the second is Adam Freeman.

2.3.1,application/x-www-form-urlencoded

The default encoding method is applicable to various types of forms except that it cannot be used to upload files to the server. The name and value of each item of data are encoded in the same way as the URL. The data of the sample form is encoded in this way, and the results are as follows:

fave=Apples&name=Adam+Freeman

The special characters have been replaced with the corresponding HTML entities. The names and values of data items are separated by an equal sign (=), and the data items in each group are separated by a symbol &.

2.3.2,multipart/form-data

It is more lengthy after coding and more complex to deal with. This is why it is generally only used for forms that need to upload files to the server.

2.3.3,text/plain

It varies from browser to browser.

2.4. Automatic completion function of control form

The browser can remember the data entered by the user in the form, and automatically use these data to help the user fill in when encountering a similar form again.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form autocomplete="off" method="post" action="http://titan:8080/form">
            <input name="fave"/>
            <input name="name"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

The autocomplete attribute allows two values: on and off. The default is on, which means that the browser is allowed to fill in the form.

The input element also has the autocomplete attribute, which can be used for the autocomplete function of a single element.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form autocomplete="off" method="post" action="http://titan:8080/form">
            <input autocomplete="on" name="fave"/>
            <input name="name"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

The autocomplete attribute of the form element sets the default behavior of the input element of the form, and the settings of each input element on this attribute can override this default behavior.

2.5. Specify the target display position of form feedback information

By default, the browser will replace the original page of the form with the information fed back by the server after submitting the form. This can be changed with the target attribute of the form element. This mechanism works the same as the target attribute of the a element.

valueexplain
_blankNew window
_parentparent window
_selfCurrent window (default)
_toptop window
Specify window
<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form target="_blank" method="post" action="http://titan:8080/form">
            <input autocomplete="on" name="fave"/>
            <input name="name"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

2.6. Set form name

The name attribute can be used to set a unique identifier for the form so that it can be divided into forms using the DOM (document object model) time zone. The name attribute is different from the global attribute id. The latter is mostly used for CSS selectors in HTML documents.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form name="fruitvote" id="fruitvote"
              method="post" action="http://titan:8080/form">
            <input name="fave"/>
            <input name="name"/>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

When the form is submitted, the value of its name attribute will not be sent to the browser, so the use of this attribute is limited to DOM and is not as important as the attribute with the same name of the input element. If the input element does not set the name attribute, the data entered by the user in it will not be sent to the server when the form is submitted.

3. Add a description label to the form

label element:

elementlabel
Element typephrase element
Allowed parent elementsAny element that can contain a phrase element.
Local attributefor,form
contentPhrase content
Label usageStart label and end label
Customary stylelabel { cursor: default; }
<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <p><label for="fave">Fruit: <input id="fave" name="fave"/></label></p>
            <p><label for="name">Name: <input id="name" name="name"/></label></p>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

In this example, each input element is matched with a label element. Note that in this example, the id attribute is set for the input element, and the for attribute of the relevant label element is set to this id value. This associates the input element with the label element.

The above code places the input element as the content of the label element. This is not a mandatory requirement. They can be defined independently. When designing complex forms, it is common for label elements to be defined independently of input elements.

4. Auto focus to an input element

Designers can focus on an input element when the form is displayed. In this way, users can directly enter data in it without having to manually select it first. The purpose of the autofocus attribute is to specify this element.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
            <p><label for="name">Name: <input id="name" name="name"/></label></p>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

As soon as the browser displays this page, it will focus on the first input element.

The autofocus attribute can only be used on one input element. If several elements have this attribute set, the browser will automatically focus on the last element.

5. Disable individual input elements

To disable the input element, you need to set its disabled attribute:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
            <p>
                <label for="name">Name: <input disabled id="name" name="name"/></label>
            </p>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

6. Group form elements

For more complex forms, you sometimes need to organize some elements together. To do this, you can use the fieldset element.

elementfieldset
Element typeStream element
Allowed parent elementsAny element that can contain a stream element, usually a descendant of a form element
Local attributename,form,disabled
contentStream content. You can include a legend element at the beginning
Label usageStart label and end label
Customary stylefieldset { display: block; margin-start: 2px;
margin-end: 2px; padding-before: 0.35em;
padding-start: 0.75em; padding-end: 0.75em;
padding-after: 0.625em; border: 2px groove; }
<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <fieldset>
                <p><label for="name">Name: <input id="name" name="name"/></label></p>
                <p><label for="name">City: <input id="city" name="city"/></label></p>
            </fieldset>
            <fieldset>
                <p><label for="fave1">#1: <input id="fave1" name="fave1"/></label></p>
                <p><label for="fave2">#2: <input id="fave2" name="fave2"/></label></p>
                <p><label for="fave3">#3: <input id="fave3" name="fave3"/></label></p>
            </fieldset>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

6.1. Add description label for fieldset element

Adding a legend element to each fieldset element can make up for the lack of relevant instructions to the user.

elementlegend
Element typenothing
Allowed parent elementsfieldset element
Local attributenothing
contentPhrase content
Label usageStart label and end label
Customary stylelegend { display: block; padding-start: 2px;
padding-end: 2px; border: none;}

The legend element must be the first child of the fieldset element:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <fieldset>
                <legend>Enter Your Details</legend>
                <p><label for="name">Name: <input id="name" name="name"/></label></p>
                <p><label for="name">City: <input id="city" name="city"/></label></p>
            </fieldset>
            <fieldset>
                <legend>Vote For Your Three Favorite Fruits</legend>
                <p><label for="fave1">#1: <input id="fave1" name="fave1"/></label></p>
                <p><label for="fave2">#2: <input id="fave2" name="fave2"/></label></p>
                <p><label for="fave3">#3: <input id="fave3" name="fave3"/></label></p>
            </fieldset>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

6.2. Disable the whole set of input elements with fieldset

You can disable multiple input elements at once by setting the disabled attribute of the fieldset element. At this point, all input elements contained in the fieldset element will be disabled.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <fieldset>
                <legend>Enter Your Details</legend>
                <p><label for="name">Name: <input id="name" name="name"/></label></p>
                <p><label for="name">City: <input id="city" name="city"/></label></p>
            </fieldset>
            <fieldset disabled>
                <legend>Vote For Your Three Favorite Fruits</legend>
                <p><label for="fave1">#1: <input id="fave1" name="fave1"/></label></p>
                <p><label for="fave2">#2: <input id="fave2" name="fave2"/></label></p>
                <p><label for="fave3">#3: <input id="fave3" name="fave3"/></label></p>
            </fieldset>
            <button>Submit Vote</button>
        </form>
    </body>
</html>

7. Using button elements

This element has three uses, and these different operation modes are set by the type attribute with three values.

valueexplain
submitIndicates that the purpose of the button is to submit a form
resetIndicates that the button is used to reset the form
buttonIndicates that the button has no specific semantics

7.1. Submit form with button element

If the type attribute of the button element is set to submit, pressing the button will submit the form containing it. This is the default behavior of a button element without the type attribute set. When using this element in this way, it has some additional attributes to use.

attributeexplain
formSpecifies the form associated with the button
formactionOverride the action attribute of the form element
formenctypeOverride the enctype attribute of the form element
formmethodOverride the method attribute of the form element
formtargetOverride the target attribute of the form element
formnovalidateOverride the novalidate attribute of the form element to indicate whether to perform client-side data validity check with.

These attributes are mainly used to override or supplement the settings on the form element, specify the URL of the form submission, the HTTP method used, the encoding method, the display location of the form feedback information, and control the client data inspection.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form>
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
            <p>
                <label for="name">Name: <input id="name" name="name"/></label>
            </p>
            <button type="submit" formaction="http://titan:8080/form"
                    formmethod="post">Submit Vote</button>
        </form>
    </body>
</html>

7.2. Reset the form with button element

If the type attribute of the button element is set to reset, pressing the button will reset all input elements in the form to their initial state. When using this element, no additional attributes are available.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
            <p>
                <label for="name">Name: <input id="name" name="name"/></label>
            </p>
            <button type="submit">Submit Vote</button>
            <button type="reset">Reset</button>
        </form>
    </body>
</html>

7.3. Use button as a general element

If the type attribute of a button element is set to button, the button element is just a button.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form method="post" action="http://titan:8080/form">
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
            <p>
                <label for="name">Name: <input id="name" name="name"/></label>
            </p>
            <button type="submit">Submit Vote</button>
            <button type="reset">Reset</button>
            <button type="button">Do <strong>NOT</strong> press this button</button>
        </form>
    </body>
</html>

It doesn't seem to make any sense. However, some operations can be performed through JacaScript. In this way, you can use the button element to implement custom behavior.

8. Use elements outside the form

In HTML4, input, button and other form related elements must be placed in the form element. In HTML5, this restriction no longer exists, and such elements can now be linked to forms anywhere in the document. To hook an element of this type with a form element that is not its ancestor element, you only need to set its form attribute to the id attribute value of the relevant form element.

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <meta name="author" content="Adam Freeman"/>
        <meta name="description" content="A simple example"/>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
    </head>
    <body>
        <form id="voteform" method="post" action="http://titan:8080/form">
            <p>
                <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
            </p>
        </form>
        <p>
            <label for="name">Name: <input form="voteform" id="name" name="name"/>
            </label>
        </p>
        
        <button form="voteform" type="submit">Submit Vote</button>
        <button form="voteform" type="reset">Reset</button>
    </body>
</html>

Keywords: Front-end html5 html

Added by curtisdw on Fri, 28 Jan 2022 14:43:37 +0200