Understanding the basics of JavaScript forms _javascript Tips

Source: Internet
Author: User
Tags button type

Htmlformelement inherited HtmlElement, its own unique attributes and methods are:

    • Acceptcharset: A character set that the server can handle, equivalent to the Accept-charset attribute of HTML
    • Action: Receives the requested URL, equivalent to the action attribute in HTML.
    • Elements: A collection of all controls in a form (htmlcollection)
    • Enctype: Type of encoding requested
    • Length: The number of controls in the form
    • Method: The type of HTTP request to send, usually a GET or post
    • Name: The names of the forms
    • Reset (): Resets all form fields to their default values
    • Submit (): Submitting Form
    • Target: The name of the window used to send the request and receive the response;

The reference to the form element can be getElementById, or it can be a numeric index or a name value in Document.forms;

First, submit the form

There are three different buttons for submitting a form:

<input type= "Submit" value= "Submit Form" >
<button type= "Submint"
>submit <input type= "image" Src= "" >

Submitting a form in this way triggers a submit event before the browser requests it to the server, so that you can validate the form data and decide whether to allow the form to be submitted, as the following code can block the form's submission:

var form = document.getElementById ("MyForm");
Form.addeventlistener ("Submit", function () {
  event.preventdefault ();
});

In addition, you can submit the form by calling the Submit () method via the JS script, and submitting the form without triggering the submit event.

var form = document.getElementById ("MyForm");
Form.submit ();

The first time a form is submitted, if there is no response for a long time, the user will become impatient, often click the Submit button repeatedly, resulting in the repeated submission of the form, so should be after the first submission of the form to disable the Submit button or use the OnSubmit event to prevent subsequent operations.

var submitbtn = document.getElementById ("submitbtn");
Submitbtn.onclick = function () {
  //processing tables and commits, etc.
  submitbtn.disabled = true;
};

Second, reset the form

Reset form should use input or button:

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

When the user clicks the reset button to reset the form, the reset event is triggered, and the reset action can be canceled when necessary:

var resetbtn = document.getElementById ("resetbtn");
Resetbtn.addeventlistener ("Reset", function () {
  event.preventdefault ();
});

Alternatively, you can reset the form by calling the Reset () method by using the JS script, which triggers the reset event when the Reset () method is invoked to reset the form.

var form = document.getElementById ("MyForm");
Form.reset ();

Three, form field

Each form has a elements property, which is a collection of all Forms (fields) in the form:

var form = document.forms["MyForm"];
var list = [];
Obtain the first field in the form
var firstName = form.elements[0];
List.push (firstname.name);
Gets the field named LastName in the form
var lastName = form.elements["LastName"];
List.push (lastname.name);
Gets the number of fields contained in the form
var fieldcount = form.elements.length;
List.push (FieldCount);
Console.log (List.tostring ()); firstname,lastname,4

Multiple form controls use a name (radio button), then the nodelist named by that name is 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>

Name is color, and returns NodeList when accessing elements["color":

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

Common form Field Properties

    • Disabled: Boolean value that indicates whether the current field is disabled;
    • Form: Pointer to the form to which the current field belongs: Read-only;
    • Name: The names of the current fields;
    • ReadOnly: Boolean value that indicates whether the current field is read-only;
    • TabIndex: Represents the Toggle (tab) Ordinal of the current field;
    • Type: the current field;
    • Value: The value of the current field being submitted to the server. For a file field, this property is read-only and contains the path of the file to the computer;

You can disable the Submit button after submitting the form via the Submit event, but you cannot use the OnClick event because onclick has "slack" in different browsers.

Common form Word Segment method

    • Focus (): activates the field so that it responds to keyboard events;
    • Blur (): lose focus, trigger, use the occasion not much;

You can add the focus () method on the Load event on the listening page:

Window.addeventlistener ("Load", function () {
  document.forms["myForm"].elements["LastName"].focus ();
});

Note that the first form field is input, and if its type attribute is "hidden", or if the display and visibility properties of the CSS property hide the field, an error is caused.

In HTML5, the new autofocus property is added to the form, and the focus is automatically moved to the corresponding field.

Autofocus
such as:

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

or detect whether the attribute is set, and then call the focus () method if it is not:

Window.addeventlistener ("Load", function () {
  var form = document.forms["MyForm"];
  if (form["LastName"].autofocus!== true) {form["LastName"].focus ();};
});

Common form field events

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

Blur: triggered when the current field loses focus;
Change :the INPUT element and the TEXTAREA element are triggered when they lose focus and the value changes, and the Select element is triggered when its options change (without losing focus);
Focus : triggered when the current field is focused;
Such as:

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") { C9/>firstname.style.backgroundcolor = "Yellow";

      };
      break;
    Case "blur":
      if (Event.target.value.length < 1) {
        FirstName.style.backgroundColor = "Red";
      } else { C16/>firstname.style.backgroundcolor = "";
      break;
    Case ' Change ':
      if (Event.target.value.length < 1) {
        FirstName.style.backgroundColor = ' red ';
      } else {
        firstName.style.backgroundColor = "";
      break;
  }
}

The above is the entire content of this article, I hope to help you learn.

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.