JavaScript Form Processing Implementation Code _ Basics

Source: Internet
Author: User
Tags numeric numeric value

Introduction to a form

In HTML, a form is represented by a <form> element, whereas in JavaScript the form corresponds to a htmlformelement type;

Htmlformelement inherits HtmlElement, so it has the default attributes that HTML elements have, and is unique to its own properties and methods;
Htmlformelement Properties and methods
description of property or method
The character set that the Acceptcharset server can handle;
The action accepts the requested URL;
Elements a collection of all the controls in the form;
The encoding type of the enctype request;
The number of controls in the length form;
The type of HTTP request to send, usually ' get ' or ' post ';
Name of the form;
The name of the window that target uses to send requests and accept responses;
Reset () resets all forms;
Submit () the form;

1. Get Forms <form> objects;
document.getElementById (' myForm '); Use ID to get <form> elements;
document.getElementsByTagName (' form ') [0]; Gets the first element in the collection of form elements;
Document.forms[0]; Gets the element using the digital subscript of forms;
document.forms[' MyForm ']; Gets the element using the name subscript of forms;

2. Submitting the form

(1). Through event objects, you can block the default behavior of submit, the default behavior of the Submit event is to carry data to the specified page;

Copy Code code as follows:

ADDEVENT (FM, ' Submit ', function (evt) {
Predef (EVT);
});

(2). We can use the Submit () method to customize the triggering of a submit event, that is, not necessarily clicking the submit button to submit;

Copy Code code as follows:

if (E.ctrlkey && e.keycode ==13) {
Fm.submit (); Judgment hold down CTRL and ENTER to trigger the commit;
}
PS: As far as possible in the form to avoid using name= "submit" or id= "submit" and so on, this will conflict with the submit () method, resulting in the failure to submit;

(3). Repeat Submission
When a piece of data is submitted to the server, there will be delays and so on, causing the user to repeatedly click Submit,
This makes repeated submissions of many of the same requests, or caused errors or write to the database a number of the same information;

Copy Code code as follows:

ADDEVENT (FM, ' Submit ', function (evt) {//Simulate server latency;
Predef (EVT);
settimeout (function () {//3 seconds before processing commits to the server;
Fm.submit ();
},3000);
});

//Resolve duplicate Submit scheme
//First: After submission, disable the click button immediately; disabled = true;  (' Sub ') document.getElementById     //Disable the button;
//Second: After submission, cancel subsequent form submission operations;
    var flag = false;                                     //Setting up a listening variable;
    if (flag = = True) return;                              // Returns the Exit event if present;
    flag = true;                                          //Otherwise determine is the first time, change the value of the listener variable;

3. Reset the form

When the user clicks the Reset button, the form is initialized;
Although this button is still retained, but the web has been very rarely used, because users fill out the information, accidentally clicked Reset will be all empty, the user experience is very poor;
There are two ways to call the Reset event: The first is to direct type= "reset", and the second is to use the Fm.reset () method call;
  <input type= "reset" value= "reset"/>          //No JS code can be achieved;
  Addevent (document, ' click ', Function () {
    fm.reset ();                   Use JS method to implement reset;
  

4. Form fields

In form processing, it is recommended that you use Htmldom, which has its own elements property, which is a collection of all elements in the form;
Fm.elements[0]; Gets the first form field element;
fm.elements[' user ']; Gets the form field element of the user that is the name value;
Fm.elements.length; Gets the number of all form fields;

(1). common form Field Properties
All form fields have the same set of attributes except the <fieldset> element;
Attribute description
Disabled Boolean value that indicates whether the current field is disabled;
The form points to a pointer to the form that the current field belongs to, read-only;
Name of the current field;
ReadOnly Boolean value that indicates whether the current field is read-only;
TabIndex represents the toggle of the current field;
The type of the current field of type;
Value of the current field;
Fm.elements[0].value; Gets and sets the value;
Fm.elements[0].disabled = true; Disables the current field;

(2). Common Form-field methods
Method Description
Focus () Navigates to the form field;
Blur () removes the focus from the element;

(3). common form Field events


Event name                       Description
blur             Triggered when the field loses focus;
change           for <input> and <textarea> elements, Triggered when the value is changed and the focus is lost; for the <select> element, it is triggered when the option is changed;
focus            triggered when the current field gets the focus;

Use the focus event to modify the background color of the text box;
  Use the Change event to modify the background color again when the user enters a non-numeric character;
  var bextbox = document.forms[0].elements[0];
    Eventutil.addhandler (textbox, ' Focus ', function (evt) {evt = Eventutil.getevent (evt);
    var target = Eventutil.gettarget (EVT);    if (Target.style.backgroundColor!= ' red ') {Target.style.backgroundColor = ' yellow ';
    When selected, the background of the text box is yellow;

  }
  });
    Eventutil.addhandler (textbox, ' Blur ', function (evt) {//Lost focus event;
    EVT = Eventutil.getevent (evt);
    var target = Eventutil.gettarget (EVT);
      if (/[^\d]/.test (Target.value)) {//input non-numeric word characters;      Target.style.backgroundColor = ' red ';
    The background of the text box turns red;
    }else{target.style.backgroundColor = ';

  }
  });
    Eventutil.addhandler (textbox, ' Change ', function (evt) {//changing value value and losing focus event;
    EVT = Eventutil.getevent (evt);
    var target = Eventutil.gettarget (EVT);      if (/[^\d]/.test (Target.value)) {Target.style.backgroundColor = ' red ';
    The text box turns red;
 }else{target.style.backgroundColor = ';   }
  }); 

Two text box script
//In HTML, there are two ways to represent a text box:

One is a single-line text box <input type= "text" >;

One is a multiline text box <textarea>;

1. Getting value value

Although <input> has literal value values, <textarea> does not, but it can get their values by value;
var TextField = fm.elements[0];
var Areafield = fm.elements[1];
Alert (textfield.value+ ', ' +areafield.value); Get the value of <input> and <textarea>;
PS: Using the value of the form is most recommended, it is the attribute in Htmldom, it is not recommended to use the standard Dom method GetAttribute ();
The reason: The modification of the Value property is not necessarily reflected in the DOM;

DefaultValue: Get the original value of value, will not change because of the change;
alert (Textfield.defaultvalue); Get the value of the original set;

2. Select text

Using the Select () method, you can select the contents of the text box and set the focus to the text box;                   Textfield.select ();

Select all of its text when the text box gets focus;
Select part of the text//When using text box content, we sometimes have to select part of the text directly, this behavior is not yet standard;
  The solution for Firefox is: Setselectionrange () method; it accepts two parameters: index and length;            Textfield.setselectionrange (0,1);
  Select the first character;  Textfield.setselectionrange (0,textfield.value.length); 
  Select All;
  IE8 The following does not support this type of writing, you can use IE range operation instead;         var range = Textfield.createtextrange ();
  Creates a text range object;                  Range.collapse (TRUE);
  Move the pointer to the starting point;             Range.movestart (' character ', 0);
  Move the pointer, character means to move verbatim;              Range.moveend (' character ', 1);
  moving end point;                     Range.Select ();

The focus designates; Select partial text-compatible functions function SelectText (text,start,stop) {if (Text.setselectionrange) {Text.setselectionrange (start,s
      top);
    Text.focus ();
      }else if (text.createtextrange) {var range = Text.createtextrange ();
      Range.collapse (TRUE);
      Range.movestart (' character ', start); Range.moveend (' character ', Sotp-start);
    Range.Select ();
  }//corresponds to the Select () method, which is a select event that can be triggered when text box text is selected;                Addevent (TextField, ' select ', function () {alert (this.value);
  IE events need to pass this to write; });
Get selected text
//Firefox offers two properties: SelectionStart and Selectionend;
  Addevent (TextField, ' select ', function () {
    alert (this.value.substring (this.selectionstart,this.selectionend)) ;
  });
  The following IE8 provides another solution: the Selection object, belonging to the document;
  This object holds the text information that the user selects within the entire document range;
  Compatible functions function
  Getselectext (text) {
    if (typeof Text.selectioinstart = = ' number ') {     //non ie;
      Return text.value.substring (text.selectionstart,text.selectionend);
    } else if (document.selection) {            //IE;
      Return Document.selection.createRange (). text;  Gets the text selected by IE
    ;
  }
  PS: There is a problem: ie in the trigger select event, after the selection of a character immediately triggered, and other browsers are selected to select the characters after releasing the mouse button and then trigger;
  Therefore, the use of alert (), resulting in cross-browser incompatibility;
  So we can assign the resulting selected text to another object;
  Addevent (TextField, ' select ', function () {
    //alert (Getselectext (this));            Resulting in inconsistent user behavior results; 
    document.getElementById (' box '). InnerHTML = Getselectext (this);
  })

3. Filter input

//in order for the text box to enter the specified character, we must verify the characters entered into the text box;
    Addevent (Areafield, ' keypress ', function (evt) {var e = evt | | window.event;      var charcode = Getcharcode (evt);
    get character encoding;              if (!/\d/.test (String.formcharcode (charcode)) && charcode>9 &&!e.ctrlkey) {predef (evt);
    Conditional blocking defaults;
  }
  });
  PS: The first half of the conditions to judge only the number can be entered, resulting in regular buttons, such as the cursor key/BACKSPACE key/delete keys and so can not be used;
  Some browsers, such as Firefox, need to liberate these keys, but not the character trigger code is 0;
  The browser before Safari3 will also be blocked, and its corresponding character encoding is all 8, so the final plus charcode>9 judgment; 
Make sure the user does not press the CTRL key; 
Prevent text boxes from cropping/copying and pasting;
The event name        indicates that
copy     is triggered when a copy operation occurs;      cut is triggered when a cropping operation occurs;
Paste     is triggered when a paste operation occurs;
Beforecopy  is triggered when a copy operation occurs;
Beforecut   is triggered when a cropping operation occurs;
Beforepaste  is triggered when a paste operation occurs;
If we want to disable crop/copy/paste, you can block the default behavior;
  Addevent (Areafield, ' cut ', function (evt) {
    predef (evt);
  });
  Addevent (Areafield, ' Copy ', function (evt) {
    predef (evt);
  });
  Addevent (Areafield, ' paste ', function (evt) {
    predef (evt);
  });

The last factor that affects input is: Input method;
Chinese input method, it is the principle of the Input Panel to store the text first, press ENTER to write English text, press the space to write the Chinese text;
Solution: Through CSS to prohibit the input method;
  style= ' ime-mode:disabled ';          CSS directly written;
  areafield.style.imemode= ' disabled ';      Set in JS;
  Ps:chrome can not prohibit the input method, so the last use of regular validation of the text entered;
  Addevent (Areafield, ' KeyUp ', function (evt) {
    this.value = This.value.replace (/[^\d]/g, "");  Replace non-digits into empty;
  

4. Auto Switch focus

In order to increase the usability of the form field, many fields will be automatically switched to the next field
  when satisfying certain conditions (such as length). <input type= ' text ' name= ' user1 ' maxlength= ' 1 '/>    //can only write 1;
  <input type= ' text ' name= ' user2 ' maxlength= ' 2 '/> <input ' text ' type= ' name= ' User3 '   
  3
  ' maxlength= function Tabforward (evt) {
    var e = evt | | window.event;
    var target = Gettarget (evt);
    Determine whether the current length is consistent with the specified length;
    if (target.value.length = = target.maxlength) {
      //traverse all fields;
      for (var i=0; i<fm.elements.length; i++) {
        //Find the current field;
        if (fm.elements[i]==target) {
          //Just move the focus to the next field;
          if (Fm.elements[i+1]) {
            fm.elements[i+1].focus ();
          }
          To return halfway;
          return;}}}
  

Three selection box script

The selection box is created by <select> and <option> elements;

Htmlselectelement objects

Attribute/Method Description
Add (New,rel) inserts the new element and specifies the position;
Multiple Boolean value, whether multiple selections are allowed;
Htmlcollection set of options <option> elements;
Remove (index) removes the option from the given position;
SelectedIndex the index of the selected item based on 0, or 1 if no item is selected;
The number of rows visible in the size selection box;

In the DOM, each <option> element has a Htmloptionelement object to access the data;
Htmloptionelement Objects
attribute Description
Index of the current option in the Options collection;
Label of the current option;
Selected Boolean value that indicates whether the current option is selected;
The text of the text option;
Values of the value option;

var city = fm.elements[' city '];      htmlselectelement;
  alert (city.options);            htmloptionscollection;
  Alert (city.options[0]);          htmloptionelement;
  alert (city.type);             Select-one;
  PS: The type attribute in the selection box may be: select-one, or it may be: select-multiple;
  This depends on whether there is a multiple attribute in the HTML code;

  alert (city.options[0].text);       Shanghai text, get the text value;
  alert (city.options[0].value);      Shanghai value, get value;
  PS: When operation Select, it is best to use htmldom, think browser compatibility is better;
  If the standard DOM is used, different browsers will result in various results;
  PS: When the selected item has no value, IE returns an empty string, and other browsers return the text value;

2. Select options

For a selection box that can only be selected, using the SelectedIndex property is easiest;

Copy Code code as follows:

Addevent (city, "Change", function () {
alert (This.selectedindex); Gets the index of the current option, starting from 0;
alert (This.options[this.selectedindex].text); Gets the text value of the current option;
alert (This.options[this.selectedindex].value); Gets the value of the current option;
});
City.selectedindex = 1; Setting SelectedIndex can locate an index;

By option attribute selected (Boolean), you can also set an index to locate, set to true;
City.options[0].selected = true; Sets the first index;

Selected and SelectedIndex differences:
1.selected is the returned Boolean value, so it is generally used in judgment;
2.selectedIndex returns the numeric value, which is generally used for setting and acquiring;

Copy Code code as follows:

Addevent (city, "Change", function () {
if (this.options[2].selected = = true) {//Determine whether the third option is selected;
Alert (' Correct! ');
}
});

3. Add options
//If a dynamic add option is required, we offer two options: DOM and option constructors;
(1). Dom
var option = document.createelement (' option ');
Option.appendchild (document.createTextNode (' Beijing text '));
Option.setattribute (' value ', ' Beijing value ');
City.appendchild (option);

(2). Option constructor
var option = new option (' Beijing text ', ' Beijing value ');
City.appendchild (option); ie appears bug;

(3). Use the Add () method to add an option:
var option = new option (' Beijing text ', ' Beijing value ');
City.add (option,0); 0, to add to the first position;
PS: In the DOM, add () two parameters are required, if not the correct index, then the second parameter set NULL, that is, the default to move to the last option;
However, the second parameter in IE is optional, so setting null means putting it in a nonexistent position, resulting in disappearance;
For compatibility, can be passed undefined compatible;
City.add (Option,null); IE does not show up;
City.add (option,undefined); Compatible

4. Removal Options

There are three ways to remove an option: Dom removes/remove () method removal and null removal;
City.removechild (City.option[0]); Dom removal;
City.remove (0); Remove () removal, recommend;
CITY.OPTIONS[0] = null; NULL removal;
PS: When the first item is removed, the following item is moved up so that the first item is removed and all is removed;

5. Move Options

If you have two selection boxes, move the first option in the first selection box to the second selection box, and the first item in the first selection box is removed;
var city = fm.elements[' city ']; The first selection box;
var info = fm.elements[' info ']; A second selection box;
Info.appendchild (City.options[0]); Move, and delete in the first selection box;

6. Arrange options

The selection box provides an index property that gets the indexed value of the current option, and the difference between the SelectedIndex is that one is the invocation of the selection box object, and the other is the invocation of the option object;

Copy Code code as follows:

var option1 = city.options[1];
City.insertbefore (Option1,city.options[option1.index-1]); Shift upward;

7. Radio button

Gets the value of the radio button by checked the property;
  for (var i=0; i<fm.sex.length; i++) {          //circular radio button; 
    if (fm.sex[i].checked = = True) {           //traverse each one to find the one in the selected state;
      alert (fm.sex[i].value);            Get a value
    ;
  }
  PS: In addition to the checked attribute, the radio button also has a defaultchecked button,
  //It gets the original Checked button object, not because of checked changes;
  if (fm.sex[i].defaultchecked = = true) {
    alert (fm.sex[i].value);
  }

8. Check button

//through checked property to get the value of the check button, var love = ';
    for (var i=0 i<fm.love.length; i++) {if (fm.love[i].checked = = True) {love = Fm.love[i].value; 
} alert (love); 

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.