search
HomeWeb Front-endHTML TutorialDeep understanding of HTML forms

Deep understanding of HTML forms

Jan 23, 2017 pm 03:54 PM
htmlform

Form elements

From HTML to HTML5, form-related elements have been greatly expanded and can basically meet our common needs. . But in actual work, Due to interaction or browser compatibility requirements, native form elements sometimes have to be extended or simulated. But before that, it is still important to clearly understand and master the various form elements. in the text, We will explain form elements (HTML5 form elements by default) in detail.

form

##● The form will automatically handle the submit event (the submit event is usually triggered by the input or button element of type=submit)

●The form will automatically do a layer of verification, and use form.novalidate to turn off the native validate

●Form will obtain the corresponding user input based on the name of each form element, and then add the form data in the form of query string to the end of the URL corresponding to the action attribute. The default request method is GET, and the default action is the current url.

●event.target.elements will return all interactive elements

<form novalidate>
  <input name=&#39;username&#39; required/>
  <input name=&#39;passworkd&#39; type=&#39;password&#39; required/>
  <input name=&#39;email&#39; type=&#39;email&#39;/>
  <input type=&#39;submit&#39; value=&#39;submit&#39;/>
</form>

You can see by running the above code that after submitting the form, the browser address will Add a query string like this?username=tom&passworkd=123&email=test%40gmail.com

Interactive elements

Need to interact with the user and obtain user input We classify this type of form elements as interactive form elements.

Some are listed below:

●input: Commonly used types include checkbox, tel, number, email, etc.

●textarea

●select

●option

Feedback elements

Form elements that simply feed back information and do not require interaction with the user, we classify them as Feedback form element.

Some are listed below:

●meter

●output

<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
    <input type=&#39;number&#39; value=&#39;50&#39; name=&#39;a&#39; />
    <input type=&#39;number&#39; value=&#39;10&#39; name=&#39;b&#39; />
    <output name=&#39;result&#39;>60</output>
</form>

For output, you can set the calculated value in form.oninput

Grouped elements

This type of form element is used to group multiple form elements. We classify them as grouped form elements.

Some are listed below:

●fieldset

●optgroup

<form>
  <select>
    <optgroup label=&#39;group1&#39;>
      <option>1</option>
      <option>2</option>
      <option>3</option>
    </optgroup>
    <optgroup label=&#39;group2&#39;>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </optgroup>
    <optgroup label=&#39;group3&#39;>
      <option>7</option>
      <option>8</option>
      <option>9</optioin>
    </optgroup>
  </select>
</form>

label

●Use for can be connected to the corresponding interactive element associated with the id

●Can be used to wrap interactive elements, including multiple, control the first one

●It is not recommended to nest labels

<form>
  <fieldset>
    <legend>Title</legend>
    <label for=&#39;radio&#39;>Click me</label>
    <input type=&#39;radio&#39; id=&#39;radio&#39;/>
  </fieldset>
</form>
<form>
  <fieldset>
    <legend>用户信息</legend>
    <label>
      男 <input type=&#39;radio&#39; name=&#39;gender&#39; id=&#39;male&#39; />
    </label>
    <label>
      女 <input type=&#39;radio&#39; name=&#39;gender&#39; id=&#39;female&#39;/>
    </label>
  </fieldset>
</form>

Use JavaScript to process forms

Abstraction of field

The most basic structure:


 field: {
    name: String,
    value: String || String[]
  }

● String[] of value is usually used, and is divided and synthesized into a String

●For names with complex structures, you can use keyPath

  const fromKeyValues = {
    &#39;user.name&#39;: &#39;Tom&#39;,
    &#39;user.phone[0].number&#39;: &#39;123456&#39;,
    &#39;user.phone[0].type&#39;: &#39;mobile&#39;
  };

  const fromValues = {
    user: {
      name: &#39;Tom&#39;,
      phone: [
        {
          number: &#39;123456&#39;,
          type: &#39;mobile&#39;
        }
      ]
    }
  };

If you are not very clear about the above code, please refer to qs

A complete implementation

●Prevent form from default submit event

●checkbox needs to be checked instead of value

● select-multiple needs to store multiple values

●Except for the above special interactive elements, the others take their values ​​from value by default

form.html

<form>
    <fieldset>
        <legend>Login</legend>
        <input name=&#39;username&#39; placeholder=&#39;username&#39; minlength=&#39;2&#39;/>
        <input name=&#39;password&#39; type=&#39;password&#39; placeholder=&#39;password&#39;/>
        <label>
            remember password            <input name=&#39;checkbox&#39; type=&#39;checkbox&#39;/>
        </label>
    </fieldset>
    <fieldset>
        <p class="gender">
            <legend>More Info</legend>
            <label>
                男                <input name=&#39;gender&#39; type=&#39;radio&#39; value=&#39;male&#39; />
            </label>
            <label>
                女                <input name=&#39;gender&#39; type=&#39;radio&#39; value=&#39;female&#39; />
            </label>
        </p>
        <select name=&#39;select&#39; multiple>
            <option>1</option>
            <optgroup label=&#39;2&#39;>
                <option>2.1</option>
                <option>2.2</option>
            </optgroup>
        </select>
    </fieldset>
    <button type=&#39;submit&#39;>Submit</button></form>

form.js

var $form = document.querySelector(&#39;form&#39;);

function getFormValues(form) {
  var values = {};
  var elements = form.elements; // elemtns is an array-like object

  for (var i = 0; i < elements.length; i++) {
    var input = elements[i];
    if (input.name) {
      switch (input.type.toLowerCase()) {
        case &#39;checkbox&#39;:
          if (input.checked) {
            values[input.name] = input.checked;
          }
          break;
        case &#39;select-multiple&#39;:
          values[input.name] = values[input.name] || [];
          for (var j = 0; j < input.length; j++) {
            if (input[j].selected) {
              values[input.name].push(input[j].value);
            }
          }
          break;
        default:
          values[input.name] = input.value;
          break;
      }
    }

  }

  return values;
}

$form.addEventListener(&#39;submit&#39;, function(event) {
  event.preventDefault();
  getFormValues(event.target);
  console.log(event.target.elements);
  console.log(getFormValues(event.target));
});

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Versatility of HTML: Applications and Use CasesThe Versatility of HTML: Applications and Use CasesApr 30, 2025 am 12:03 AM

HTML is not only the skeleton of web pages, but is more widely used in many fields: 1. In web page development, HTML defines the page structure and combines CSS and JavaScript to achieve rich interfaces. 2. In mobile application development, HTML5 supports offline storage and geolocation functions. 3. In emails and newsletters, HTML improves the format and multimedia effects of emails. 4. In game development, HTML5's Canvas API is used to create 2D and 3D games.

What is the root tag in an HTML document?What is the root tag in an HTML document?Apr 29, 2025 am 12:10 AM

TheroottaginanHTMLdocumentis.Itservesasthetop-levelelementthatencapsulatesallothercontent,ensuringproperdocumentstructureandbrowserparsing.

Are the HTML tags and elements the same thing?Are the HTML tags and elements the same thing?Apr 28, 2025 pm 05:44 PM

The article explains that HTML tags are syntax markers used to define elements, while elements are complete units including tags and content. They work together to structure webpages.Character count: 159

What is the significance of <head> and <body> tag in HTML?What is the significance of <head> and <body> tag in HTML?Apr 28, 2025 pm 05:43 PM

The article discusses the roles of <head> and <body> tags in HTML, their impact on user experience, and SEO implications. Proper structuring enhances website functionality and search engine optimization.

What is the difference between <strong>, <b> tags and <em>, <i> tags?What is the difference between <strong>, <b> tags and <em>, <i> tags?Apr 28, 2025 pm 05:42 PM

The article discusses the differences between HTML tags , , , and , focusing on their semantic vs. presentational uses and their impact on SEO and accessibility.

Please explain how to indicate the character set being used by a document in HTML?Please explain how to indicate the character set being used by a document in HTML?Apr 28, 2025 pm 05:41 PM

Article discusses specifying character encoding in HTML, focusing on UTF-8. Main issue: ensuring correct display of text, preventing garbled characters, and enhancing SEO and accessibility.

What are the various formatting tags in HTML?What are the various formatting tags in HTML?Apr 28, 2025 pm 05:39 PM

The article discusses various HTML formatting tags used for structuring and styling web content, emphasizing their effects on text appearance and the importance of semantic tags for accessibility and SEO.

What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?Apr 28, 2025 pm 05:39 PM

The article discusses the differences between HTML's 'id' and 'class' attributes, focusing on their uniqueness, purpose, CSS syntax, and specificity. It explains how their use impacts webpage styling and functionality, and provides best practices for

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.