Basic knowledge of JavaScript forms, javascript forms

Source: Internet
Author: User

Basic knowledge of JavaScript forms, javascript forms

HTMLFormElement inherits HTMLElement. Its unique attributes and methods include:

  • AcceptCharset: the character set that the server can process. It is equivalent to the accept-charset feature of HTML.
  • Action: The URL that receives the request, which is equivalent to the action feature in HTML.
  • Elements: HTMLCollection of all controls in a form)
  • Enctype: the encoding type of the request.
  • Length: number of controls in the form
  • Method: The type of HTTP request to be sent, usually get or post.
  • Name: form name
  • Reset (): resets all form fields to the default value.
  • Submit (): submit a form
  • Target: the name of the window used to send requests and receive responses;

The reference to the form element can be getElementById or a numerical index or name value in document. forms;

I. submit a form

There are three buttons for submitting a form:

<input type="submit" value="Submit Form"><button type="submint">Submit Form</button><input type="image" src="">

The above method triggers the submit event before the browser request is sent to the server, so that you can verify the form data and decide whether to allow the form to be submitted, the following code prevents form submission:

var form = document.getElementById("myForm");form.addEventListener("submit", function () {  event.preventDefault();});

In addition, you can use a js script to call the submit () method to submit a form. When you call the submit () method to submit a form, the submit event is not triggered.

var form = document.getElementById("myForm");form.submit();

After a form is submitted for the first time, if the user does not respond for a long time, the user will become impatient and often click the submit button multiple times, leading to repeated form submission, therefore, you should disable the submit button or use the onsubmit event to prevent subsequent operations after the form is submitted for the first time.

Var submitBtn = document. getElementById ("submitBtn"); submitBtn. onclick = function () {// submitBtn. disabled = true ;};

Ii. Reset the form

Input or button should be used to reset the form:

<input type="reset" value = "Reset Form"><button type="reset">Reset Form</button>

When you click the reset button to reset the form, the reset event is triggered. You can cancel the reset operation when necessary:

var resetBtn = document.getElementById("resetBtn");resetBtn.addEventListener("reset", function () {  event.preventDefault();});

In addition, you can use a js script to call the reset () method to reset the form. When you call the reset () method to reset the form, the reset event is triggered.

var form = document.getElementById("myForm");form.reset();

3. Form Fields

Each form has an elements attribute, which is a set of All Forms (fields) in the form:

Var form = document. forms ["myForm"]; var list = []; // obtain the first field var firstName = form in the form. elements [0]; list. push (firstName. name); // obtain the var lastName = form field named lastName in the form. elements ["lastName"]; list. push (lastName. name); // obtain the number of fields contained in the form var fieldCount = form. elements. length; list. push (fieldCount); console. log (list. toString (); // firstName, lastName, 4

If multiple Form Controls use one name (single-choice button), The NodeList with the name will be returned:

<form id="myForm" name="myForm">  <ul>    <li><input type="radio" name="color" value="red">red</li>    <li><input type="radio" name="color" value="yellow">yellow</li>    <li><input type="radio" name="color" value="blue">blue</li>  </ul>  <button type="submint">Submit Form</button>  <button type="reset">Reset Form</button></form>

When elements ["color"] is accessed, NodeList is returned:

var list = [];var form = document.forms["myForm"];var radios = form.elements["color"];console.log(radios.length) //3

Common form field attributes

  • Disabled: Boolean value, indicating whether the current field is disabled;
  • Form: pointer to the form to which the current field belongs: Read-only;
  • Name: name of the current field;
  • ReadOnly: Boolean value, indicating whether the current field is read-only;
  • TabIndex: the number of tabs for the current field;
  • Type: the type of the current field;
  • Value: the value that the current field is submitted to the server. For file fields, this attribute is read-only and contains the path of the file on the computer;

You can disable the submit button after submitting a form through the submit event, but you cannot use the onclick event because onclick has a "time difference" in different browsers ";

Common form fields

  • Focus ():Activate the field so that it can respond to keyboard events;
  • Blur ():No focus, trigger; not used in many cases;

You can add the focus () method to the load event of the listener page:

window.addEventListener("load", function () {  document.forms["myForm"].elements["lastName"].focus();});

Note that the first form field is input. If the type attribute is "hidden" or the display and visibility attributes of the css attribute hide this field, an error will occur.

In HTML5, the autofocus attribute is added to the form to automatically move the focus to the corresponding field.

Autofocus
For example:

<input type="text" name="lastName" autofocus>

Or check whether this attribute is set. If not, call the focus () method:

window.addEventListener("load", function () {  var form = document.forms["myForm"];  if (form["lastName"].autofocus !== true) {    form["lastName"].focus();  };});

Common form field events

In addition to mouse and keyboard changes and HTML events, all form fields support the following three events:

Blur:Triggered when the current field loses focus;
Change:The input and textarea elements are triggered when they lose focus and the value changes; the select element is triggered when their options change (or if they do not lose focus );
Focus:Triggered when the current field obtains the focus;
For example:

var form = document.forms["myForm"];var firstName = form.elements["firstName"];firstName.addEventListener("focus", handler);firstName.addEventListener("blur", handler);firstName.addEventListener("change", handler);function handler() {  switch (event.type) {    case "focus":      if (firstName.style.backgroundColor !== "red") {        firstName.style.backgroundColor = "yellow";      };      break;    case "blur":      if (event.target.value.length < 1) {        firstName.style.backgroundColor = "red";      } else {        firstName.style.backgroundColor = "";      };      break;    case "change":      if (event.target.value.length < 1) {        firstName.style.backgroundColor = "red";      } else {        firstName.style.backgroundColor = "";      };      break;  }}

The above is all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • JS form usage Summary
  • A simple example of Javascript and Java to obtain various form information
  • Summary of three methods for submitting forms after js validation form
  • Jquery serialized form json data returned after ajax submission
  • Jquery automatically encapsulates form into json
  • Js clear form content example
  • AngularJS implements Form Verification
  • JavaScript determines which radio button is selected when a form is submitted
  • How to use JavaScript to obtain the values of all elements in a form

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.