H5 learning pen 3: HTML5 forms and other new and improved elements

1. Add new elements and attributes

New attribute

1. Form attribute of elements in the form: in HTML5, subordinate elements in the form can be written outside the form.

 <form id="testform">
<input type="text"> 
</form> 
<!-- Below textarea You don't have to write it on it form In form --> 
<textarea form="testform"></textarea>

2. formaction attribute of elements in the form: different fromaction attributes can be added to all submit buttons, such as,, so that the form can be submitted to different pages when clicking different buttons.

<form id="testform" action="server.jsp">
<input type="submit" name="s1" value="v1" formaction="s1.jsp">Submit to s1
<input type="submit" name="s2" value="v2" formaction="s2.jsp">Submit to s2
<input type="submit" name="s3" value="s3" formaction="s3.jsp">Submit to s3 </form> 

3. formmethod attribute of elements in the form: formulate different submission methods (POST or GET) for each form element

<form id="testform" action="serve.jsp">
full name:<input type="text" name="name"><br>
<input type="submit" value="POST Submit" formmethod="post">
<input type="submit" value="GET Submit" formmethod="get"> </form>

4. formenctype attribute of elements in the form: different coding methods are formulated for form elements. Before HTML5, there is an enctype attribute in the form, which is used to specify how to encode the data before the form is submitted to the server. It has three values:

① Application / x-www-form-urlencoded (default)
② Multipart / form data (file upload)
③text/plain

<form action="server.jsp" method="post">
    <input type="text" name="name" value="test"><br>
    File:<input type="file" name="files">
    <input type="submit" value="upload" formaction="uploadFile.jsp" formenctype="multipart/form-data">
    <input type="submit" value="Submit">
</form>

5. formtarget attribute of elements in the form: it is used to specify where to open the page to be loaded after the form is submitted. Its attribute values are as follows:

①_ blank: open in a new window
②_ self: open in this window (default)
③_ Parent: Opens in the parent window of the current window
④_ top: open in the current window
⑤ framename: open in the specified frame

<form id="testform" action="server.js">
  <input type="submit" name="s1" value="v1" formaction="s1.jsp"
  formtarget="_self">Submit to s1
  <input type="submit" name="s2" value="v2" formaction="s2.jsp"
  formtarget="_blank">Submit to s2
</form>

6. Autofocus attribute of elements in the form: after adding autofocus attribute to text box, selection box or button box, these controls will automatically obtain focus when the page is opened. Only one control on a page can have the autofocus property.

<input type="text" autofocus>

7. required attribute of elements in the form: the input box to which this attribute is applied. When the form is submitted, it will check whether the content has been entered. If there is no content, it will automatically prompt the user for input.

<input type="text" required>

8. Labels attribute of elements in the form: define a labels attribute for all form controls that can use label elements, and the attribute value is a NodeList object, which represents the collection composed of label elements bound to this element. (hard to understand)

See page 57 of HTML5 and CSS3 authoritative guide for code details
9. Control attribute of label: place a form element inside the label (label element) and access the form through the control attribute of the label.

<!DOCTYPE html>
<html>
  <head>
    <title>Tagged control Property usage example</title>
    <meta charset="UTF-8">
    <script>
      function setValue () {
        var label = document.getELementById("label");
        var textbox = label.control;
        textbox.value = "621000";
      }
    </script>
  </head>
 
  <body>
    <form>
      <label id="label">
        Zip code:<input type="text" maxlength="6">
        <small>Please enter six digits</small>
      </label>
      <input type="button" value="Set default values" onclick="setValue()">
    </form>
  </body>
</html>

10. Placeholder attribute of text box: the input prompt displayed when the text box (text or textarea) is not input. In addition, we can control the display style of placeholder in CSS

<input type="text" placeholder="Input Me">

11. List attribute of text box: a list attribute is added to the single line text box. The value of this attribute is the id of a datalist element. This datalist element list provides convenient choices for user input. We can also use CSS to control that the datalist is not displayed.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>list Attribute example</title>
  </head>
  <body>
    text: <input type="text" name="greeting" list="greetings">
    <!-- use style="display:none;"take datalist The element is set to not display -->
    <datalist id="greetings" style="display:none;">
      <option value="Good Morning">Good Morning</option>
      <option value="Hello">Hello</option>
      <option value="Good Afternoon">Good Afternoon</option>
    </datalist>
  </body>
</html>

12. autocomplete attribute of text box: it can specify three values of 'on', 'off' and '. When it is specified as' on', it can explicitly specify the data list of candidate input, and use datalist element and list attribute to provide the data list of candidate input

<iniput type="text" name="geenting" autocomplete="on" list="greetings">

13. Pattern attribute of text box: use the pattern attribute on the input element and set its value to a regular expression in a certain format. When submitting, the user's input will be checked to check whether its input content conforms to the given format.

<form>
  Please enter the content in the specified format:<input type="text" pattern="[0-9][A-Z]{3}" name="part">
  <input type="submit">
</form>

14. selectionDirection attribute of text box: for input element and textarea element, when the user selects the text part with the mouse, this attribute can be used to obtain the selected direction. When the text is selected in the forward direction, the attribute value is' forward 'and' backward 'in the reverse direction.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>selectionDirection Property usage example</title>
    <script>
      function alertSelectionDirection () {
        var control = document.forms[0]['text'];
        var direction = control.selectionDirection;
        alert(direction);
      }
    </script>
  </head>
  <body>
    <form>
      <input type="text" name="text">
      <input type="button" value="Click me" onclick="alertSelectionDirection()">
    </form>
  </body>
</html>

15. Indeterminate attribute of check box: the previous check box has only two states: checked and unchecked. In HTML5, the indeterminate attribute can be used for this element through JavaScript to indicate that the check box is in the "whether to select or not" state

<input type="checkbox" indeterminate id="cb">indeterminate Attribute test
<script>
  var cb = document.getElementById('cb');
  //Set the indeterminate property to true
  cb.indeterminate = true;
</script>

16. Height attribute and width attribute of image submission button: for the input element of image type, HTML5 adds width and height attributes to specify the width and height of the image respectively

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>image Type input Element usage example</title>
  </head>
  <body>
    <form>
      full name: <input type="text" name="name">
      <input type="image" src="edit.gif" alt="edit" width=23 height=23>
    </form>
  </body>
</html>

17. maxlength attribute and wrap attribute of textarea element:

The maxlength attribute uses an integer value to set the maximum number of characters that can be entered for this textarea element
wrap attribute can specify two values of soft and hard: when it is specified as hard, the automatic line feed of user input will be recorded, that is, a line feed flag will be inserted at the line feed, so the data obtained in the background will also be line feed, while soft will not have this effect. When using the hard attribute, you must specify the cols attribute value of textarea

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>textarea Element added maxlength Attribute and wrap attribute</title>
  </head>
  <body>
    <form action="test.php" method="post">
      <textarea name="name" maxlength=100 rows=5 wrap="hard" cols=5>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

New and improved input element types

  • search: similar to the text text box, it is dedicated to searching
  • tel: similar to the text text box, it is dedicated to telephone numbers
  • url: similar to the text box, it requires the user to enter the content in url format
  • Email: similar to the text box, it requires the user to enter the content in the correct email format
  • Date, month, week, time, dateimte local: various date and practice input text boxes
  • Number: similar to text text box, but its content must be a number, otherwise it will be empty after submission
  • Range: a text box that allows you to enter only a range of values, with min attribute and max attribute
  • Color: color selection text box

The new properties above will behave differently in each browser

1.url type: the input of url type is specially used to enter the text box of url address. If the input content format is inconsistent, it is not allowed to submit

<input type="url" name="url" value="http://www.microsoft.com">

2.email type: the input of email type is specially used to enter the text box of email address. If the input content format is inconsistent, it is not allowed to submit. It also has a multiple attribute, which allows users to enter multiple email addresses, separated by commas

<input type="email" name="email" value="3494688@qq.com">
<input type="email" name="emails" multiple value="3494688@qq.com,kaindy7633@gmail.com">

3.date type: date type input allows the user to input date type content, which is usually displayed to the user in the form of calendar to facilitate the user's selection and input.

<input type="date" name="date" value="2016-0101">

4.time type: the input of time type is a text box specially used to input time, and the validity of the input content will be checked when submitting.

<input type="time" name="time" value="10:00">

5. Datetime local type: datetime local type is a text box specially used to input local date and time, and the validity of the input will be checked when submitting.

<input type="datetime-local" name="datetime-local" value="2016-01-01T10:00:15">

6.month type: month type is specially used to enter the text box of the month and check the validity when submitting

<input type="month" name="month" value="2015-10">

7.week type: the week type is specially used to enter the text box of the week number and check the validity when submitting

<input type="week" name="week" value="2010-W40">

8. Attributes of date and time type elements

① All elements used to enter date and time (date, time, datetime local, month, week) have a step attribute, which is used to limit the user's selection

<input type="date" name="date" step="3">

For the datetime local attribute, using an integer multiple of step=60 or 60 indicates that the minimum input unit is minutes, while when it is not an integer multiple, it indicates that a value in seconds can be entered

② In JavaScript, you can change these input values with step attribute by using stepUp method and stepDown method

document.forms[0].date.stepUp(5);

③ When using these date and time elements, you can limit the range of input values by using the min attribute and the max attribute

<input type="date" name="date" min="2016-01-01" max="2016-01-31">

④ All elements used to enter date and time have a valueAsDate attribute, which is used to set or get UTC date and time

⑤ All elements used to input date and time have a valueAsNumber attribute, which is used to set or obtain the converted integer value of the date and time set in the element (the number of milliseconds after 0:0:0 on January 1, 1970), that is, the timestamp.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UFT-8">
    <title>valueAsDate Property usage example</title>
  </head>
  <body>
    <form>
      <input type="date" name="date" id="date">
      <input type="button" value="Click me" onclick="alert(document.getElementById('date').valueAsNumber)">
    </form>
    
    <script>
      document.getElementById('date').valueAsDate = new Date();
    </scriipt>
  </body>
</html>

9.number type: a text box specially used to input numbers, which will be checked during submission. If it does not match, it will be submitted with blank content. The number type also has max, min, and step attributes

<input type="number" name="number" value="25" max="100" min="10" step="5">

JavaScript provides the valueAsNumber attribute for the number element, which can be used to set and read the value in the element

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>valueAsNumber Property usage example</title>
    <script>
      function sum () {
        var number1 = document.getElementById('number1').valueAsNumber;
        var number2 = document.getElementById('number2').valueAsNumber;
        document.getElementById('result').valueAsNumber = number1 + number2;
      }
    </script>
  </head>
  <body>
    <form>
      <input type="number" id="number1"> + 
      <input type="number" id="number2"> =
      <input type="number" id="result" readonly>
      <input type="button" value="calculation" onclick="sum();">
    </form>
  </body>
</html>

10.range type: a text box that allows you to enter only a range of values. It has max attribute, min attribute and step attribute

<input type="range" name="range" value="25" max="100" min="10" step="5">

11.search type: it is a text box specially used to enter search keywords. The appearance can be rewritten with CSS Style:

input[type="search"] {-webkit-appearance: textfield;}

12.tel type: it is designed as a special text box for entering phone numbers, but it has no verification rules. We can specify to verify the user's input through the pattern attribute.

13.color type: the input element of color type is used to select color, which provides a color selector.

Select background:
<input type="color" onchange="document.body.style.backgroundColor=document.getElementById('currentColor').textContent = this.value;">
<span id="currentColor"></span>

14. Simple form example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Simple form example</title>
  </head>
  <body>
    <form name="form1">
      <label for="username">full name:</label>
      <input type="text" name="username" id="username" required><br>
       <label for="age">Age:</label>
       <input type="number" name="age" id="age" min="0" max="100"><br>
       <label for="birthday">date of birth:</label>
       <input type="date" name="birthday" id="birthday"><br>
       <label for="Email">Email: </label>
       <input type="email" name="email" id="email" required><br>
       <label for="url">Personal homepage:</label>
       <input type="url" name="url" id="url"><br>
       <label for="memo">Personal profile:</label>
       <textarea name="memo" id="memo" required></textarea><br>
       <input type="submit">   
    </form>
  </body>
</html>

Use styles for new form elements

Append of output element
The output element defines different types of output, such as calculation results or script output, which must be written inside the form

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>output Element example</title>
    <script>
      function value_change() {
         var number = document.getElementById('range1').value;
         document.getElementById('output1').value = number;
      }
    </script>
  </head>
  <body>
    <form id="testform">
      Please select a value:
      <input type="range" id="range1" min=0 max=100 step=5 value=10 onchange="value_change()">
      <output id="output1">10</output>
    </form>
  </body>
</html>

2. Form validation

1. Automatic verification
In HTML5, the method of using attributes on elements can realize the automatic verification function when submitting forms

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Form validation example</title>
  </head>
  <body>
    <form method="post">
      <input type="text" required pattern="^\w.*$">
      <input type="submit">
    </form>
  </body>
</html>

2. Cancel verification
There are two ways to cancel form validation:

  • Use the novalidate attribute of the form element to turn off the whole form validation
  • Use the formnovalidate attribute of the input element or the submit element

3. Explicit validation
checkValidity method, which can be called to explicitly verify the validity of all element contents or single element contents in the form, and it returns Boolean values.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>checkValidity Examples</title>
    <script>
      function check() {
        var email = document.getElementById('email');
        if(email.value == '') {
          alert('Please enter Email address');
          return false;
        } else if(!email.checkValidity()) {
          alert('Please enter the correct email address');
          return false;
        } else {
          alert('You entered Email Address valid');
        }
      }
    </script>
  </head>
  <body>
    <form id="testform" onsubmit="return check();" novalidate="true">
      <label for="email">Email:</label>
      <input type="email" name="email" id="email">
      <input type="submit">
    </form>
  </body>
</html>

3. Enhanced page elements

1. New figure element and figcaption element
The figure element is used to represent block independent content on the page. It can represent pictures, statistical charts or sample code

The figcaption element represents the title of the figure element. Its subordinate and figure must be written inside the figure element

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>figure Element example</title>
  </head>
  <body>
    <figure>
      <img src="s1.jpg" alt="forest">
      <figcaption>forest</figcaption>
    </figure>
  </body>
</html>

2. New details element and summary element
The details element is used to identify the child elements inside the element, which can expand and shrink the display element.

The summary element is subordinate to the details element. When you click the content text in the summary element with the mouse, all other subordinate elements in the details element will expand or contract.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>details Element usage example</title>
    <script>
      function detail_ontoggle(detail) {
        var p = document.geElementById('p');
        if(detail.open) {
          p.style.visibility = 'visible';
        } else {
          p.style.visibility = 'hidden';
        }
      }
    </script>
  </head>
  <body>
    <details id="detail" ontoggle="detail_ontoggle(this)" style="curosr:pointer">
      <summary>Jingwu Fengyun</summary>
      <p id="p" style="visibility:hidden">Chen Zhen (Donnie Yen) created Hongkou Daochang to avenge the killing of the master...(Introduction to Jingwu Fengyun film)</p>
    </details>
  </body>
</html>

3. New mark element
The mark element indicates what needs to be highlighted or highlighted in the page

<p><mark>HTML5</mark>It's been nearly ten years Web The biggest leap in development standards</p>

4. New progress element
The progress element represents the completion progress of a task. This progress can be uncertain, indicating that the progress is in progress.

This element has two attributes indicating the completion of the current task. The value attribute indicates how much work has been completed, and the max attribute indicates how much work has been completed in total.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>progress Examples of using elements</title>
    <script>
      var progressBar = document.getElementById('p');
      function button_onlcick() {
        var progressBar = document.getElementById('p');
        progressBar.getElementByTagName('span')[0].textContent = "0";
        for(var i=0; i<=100; i++) {
          updateProgress(i);
        }
      }
      function updateProgress(newValue) {
        var progressBar = document.getElementById('p');
        progressBar.value = newValue;
        progressBar.getElementByTagName('span')[0].textContent = newValue;
      }
    </script>
  </head>
  <body>
    <section>
      <h2>progress Examples of using elements</h2>
      <p>Percent complete:<progress id="p" max=100><span>0</span>%</progress></p>
      <input type="button" onclick="button_onclick()" vlaue="Please click">
    </section> 
  </body>
</html>

5. New meter element
The meter element represents the quantity value within the specified range, such as disk usage, voting proportion, etc. it has 6 attributes

  • Value: the actual value marked in the element
  • min: the minimum value allowed when specifying the specified range
  • max: the maximum value allowed when specifying the specified range
  • low: the lower limit of the specified range, which must be less than or equal to the value of the high attribute
  • high: the upper limit of the specified range
  • optimum: the best value. The attribute value must be between the min attribute value and the max attribute value
<p>Disk usage:<meter value="40" min="0" max="160">40/160</meter>GB</p>

6. New dialog element
The dialog element represents a dialog box

By default, the dialog element is hidden. We can use the show method of the element to display the dialog element and the close method to hide the dialog element in JavaScript code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="button" value="open a dialog box" onclick="document.getElementById('dg').show();">
    <dialog id="dg" style="width: 9%; text-align: center;">
      <h1> User login </h1>
      <main>
        <form class="" action="index.html" method="post">
          <label for="txtName" value="user name">
            <input type="text" id="txtName">
          </label><br>
          <label for="txtPassword" value="password">
            <input type="password" id="txtPassword">
          </label><br>
          <input type="button" value="Sign in">
          <input type="button" value="close" onclick="document.getElementById('dg').close();">
        </form>
      </main>
    </dialog>
  </body>
</html>

You can use the showModal method of the dialog element to display the dialog element in the form of a modal dialog box

<input type="button" value="open a dialog box" onclick="document.getElementById('dg').showModal();">

If you want to display the dialog box when the page opens, you can use the open attribute of the dialog element

<dialog id="dg" open style="width:9%;text-align:center;">

You can use the returnValue attribute of the dialog element to set or return a value for the dialog

<input type="button" value="open a dialog box" onclick="document.getElementById('dg').show(); document.getElementById('dg').returnValue='Returned value';">
 
<input type="button" value="close" onclick="document.getElementById('dg').close(); alert(document.getElementById('dg').returnValue);">

7. Improved element a
In HTML5, the download attribute is added to the a tag. After users click the link with this attribute, they will directly download the resource file pointed to by the link.

<a href="html5.jpg" download="HTML5 Authoritative guide"><img src="html5.jpg"></a>

After users click the link, they will directly download HTML5 Jpg this picture file, and the file name is' HTML5 authoritative guide '

8. Improved ol list
In HTML5, the start attribute and the reversed attribute are added to the ol element

If you want the list number not to start with 1, you can use the start attribute to customize the start number

<ol start=5>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
</ol>

If you need to reverse number the list, you can use the returned attribute of the ol list

<ol start=5 resersed>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
  <li>List content</li>
</ol>

9. Improved dl list
The dl list can be used to define the interpretation of terms on articles or web pages

<dl>
  <dt><dfn>RSS</dfn></dt>
  <dd>RSS Also called aggregation RSS Is an easy way to share content online....</dd>
  <dt><dfn>Blog</dfn></dt>
  <dd>Blog, also translated as weblog, blog or blog, is a kind of blog usually managed by individuals...</dd>
</dl>

It can also be used to represent the auxiliary information of the content in some pages or article elements

<dl>
  <dt>author</dt>
  <dd>Kaindy</dd>
  <dt>press</dt>
  <dd>Machinery Industry Press</dd>
  <dt>category</dt>
  <dd>Network development</dd>
</dl>

10. Strictly restricted cite elements
The cite element represents the title of a work (a book, an article, a song). In HTML4, cite can be used to represent the author, but in HTML5, it is clearly stipulated that the cite element cannot be used to represent any person's name, including the author.

<p>My favorite movie is starring Donnie Yen<cite>Jingwu Fengyun</cite>. </p>

11. Redefined small element
The small element defines more specific elements specifically used to identify the so-called "small print", which are usually used in the text of disclaimers, precautions, legal provisions, copyright related notices, etc.

12. iframe elements with enhanced security
Slightly

13. Enhanced script elements
In HTML5, for script elements, async attribute and defer attribute are added. Their functions are to speed up the loading speed of the page, so that the reading of script code will no longer hinder the loading of other elements on the page.

When we use the async attribute, the onload event handler will be executed immediately after the script file is downloaded

<script async src="xxx.js" onload="myInit1()"></script>
<script async src="aaa.js" onload="myInit2()"></script>

When we use the defer attribute, the onload event handler of the script file will not be executed immediately after the script file is downloaded. Instead, the onload event handler of the script file will not be executed until all pages are loaded

<script defer src="xxx.js" onload="myInit1()"></script>
<script defer src="aaa.js" onload="myInit2()"></script>

Tags: html5

Posted by Skull on Wed, 11 May 2022 16:04:09 +0300