JavaScript form processing implementation code, javascript form
1. Form Introduction
In HTML, the form is represented by the <form> element, while in JavaScript, the form corresponds to the HTMLFormElement type;
// HTMLFormElement inherits HTMLElement. Therefore, it has default attributes of HTML elements, and does not have its own attributes and methods;
HTMLFormElement attributes and Methods
Attribute or method description
Character Set that can be processed by the acceptCharset server;
The URL that the action accepts the request;
Set of all controls in the elements form;
Encoding type of the enctype request;
The number of controls in the length form;
The type of the HTTP request to be sent by method, usually 'get' or 'post ';
Name form name;
Target is the window name used to send requests and receive responses;
Reset () resets all forms;
Submit () submission form;
1. Obtain the form <form> object;
Document. getElementById ('myform'); // use the ID to obtain the <form> element;
Document. getElementsByTagName ('form') [0]; // obtain the first element in the form Element Set;
Document. forms [0]; // use the digital subscript of forms to obtain the element;
Document. forms ['myform']; // obtain the element using the name subscript of forms;
2. submit the form
(1). Through the event object, you can prevent the default behavior of the submit event. The default behavior of the submit event is to carry data to jump to the specified page;
Copy codeThe Code is as follows:
AddEvent (fm, 'submit ', function (evt ){
PreDef (evt );
});
(2) We can use the submit () method to customize the trigger submit event. That is to say, you do not have to click the submit button to submit the event;
Copy codeThe Code is as follows:
If (e. ctrlKey & e. keyCode = 13 ){
Fm. submit (); // determines that the submission is triggered by pressing ctrl and enter;
}
// PS: Do not use names such as name = "submit" or id = "submit" in the form. This conflicts with the submit () method, and thus cannot be submitted;
(3). Submit again
// When a piece of data is submitted to the server, there will be a delay that is not reflected for a long time. As a result, the user will not stop clicking and submitting,
// So that many identical requests are submitted repeatedly, or errors are caused or multiple identical information records are written into the database;
Copy codeThe Code is as follows:
AddEvent (fm, 'submit ', function (evt) {// simulate server latency;
PreDef (evt );
SetTimeout (function () {// 3 seconds before processing and submission to the server;
Fm. submit ();
},3000 );
});
// Solution repeated submission
// Method 1: Immediately disable the click button after submission;
Document. getElementById ('sub'). disabled = true; // disable the button;
// Method 2: Cancel subsequent form submission after submission;
Var flag = false; // set a listener variable;
If (flag = true) return; // if yes, the exit event is returned;
Flag = true; // otherwise, it is the first time to change the value of the listener variable;
3. Reset the form
// When you click the reset button, the form is initialized. // although this button is retained, the Web is rarely used, if you Click reset accidentally, all items will be cleared and the user experience will be poor. // There are two ways to call the reset event: the first is to directly type = "reset; the second is to use fm. call the reset () method. <input type = "reset" value = "reset"/> // this can be achieved without JS Code. addEvent (document, 'click', function () {fm. reset (); // reset using JS ;});
4. form fields
// In form processing, HTMLDOM is recommended. It has its own elements attribute, which is a set of all elements in the form;
Fm. elements [0]; // obtain the element of the first form field;
Fm. elements ['user']; // obtain the form field element whose name value is user;
Fm. elements. length; // obtain the number of all form fields;
(1). Common form field attributes
// All form fields have the same attributes except the <fieldset> element;
Attribute description
The Boolean value of disabled, indicating whether the current field is disabled;
Form pointer to the form to which the current field belongs, read-only;
Name: the name of the current field;
ReadOnly Boolean value, indicating whether the current field is read-only;
TabIndex indicates the switching of the current field;
Type: the type of the current field;
The value of the current field;
Fm. elements [0]. value; // obtain and set value;
Fm. elements [0]. disabled = true; // disable the current field;
(2). Common form field methods
Method description
Focus () locates the focus in the form field;
Blur () removes focus from the element;
(3). Common form field events
Event Name Description
Triggered when the field loses focus;
Change is triggered when the <input> and <textarea> elements change the value and lose the focus. For <select> elements, it is triggered when the option is changed;
Triggered when the current field of focus 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 inputs non-numeric characters; var bextbox = document. forms [0]. elements [0]; EventUtil. addHandler (textbox, 'core', 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) {// events with no focus; evt = EventUtil. getEvent (evt); var target = EventUtil. getTarget (evt); if (/[^ \ d]/. test (target. value) {// when a non-numeric character is entered; target. style. backgroundColor = 'red'; // the background of the text box turns red;} else {target. style. backgroundColor = '';}}); EventUtil. addHandler (textbox, 'change', function (evt) {// Changes the value and loses the 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 = '';}});
2 text box script
// In HTML, there are two ways to express the text box:
// One is the single-line text box <input type = "text">;
// Multi-line text box <textarea>;
1. Get value
// Although <input> has literal value while <textarea> does not, value can be obtained through value;
Var textField = fm. elements [0];
Var areaField = fm. elements [1];
Alert (textField. value + ',' + areaField. value); // obtain the value values of <input> and <textarea>;
// PS: the form value is the most recommended. It is an attribute in HTMLDOM. The standard DOM method getAttribute () is not recommended ();
// Cause: the modification to the value attribute is not necessarily reflected in the DOM;
// DefaultValue: gets the original value, and does not change because of the value;
Alert (textField. defaultValue); // obtain the initial value;
2. Select text
// Using the select () method, you can select the content in the text box and set the focus to the text box; textField. select (); // select all text in the text box when the focus is obtained; // select some text. // when using the text box content, we sometimes need to directly select some text, there is no standard for this behavior; // the Firefox solution 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; // This method is not supported below IE8, and can be replaced by the range operation of IE; var range = textField. createTextRange (); // create a text range object; range. collapse (true); // move the pointer to the starting point; range. moveStart ('character ', 0); // move the pointer. character indicates to move word by word; range. moveEnd ('character ', 1); // move the endpoint; range. select (); // select the focus; // select some text compatible functions: function selectText (text, start, stop) {if (text. setSelectionRange) {text. setSelectionRange (start, stop); 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. It is a select event that can be triggered after the text in the text box is selected. addEvent (textField, 'select', function () {alert (this. value); // The IE event can be written only when this is passed ;});
// Obtain the selected text // Firefox provides two attributes: selectionStart and selectionEnd; addEvent (textField, 'select', function () {alert (this. value. substring (this. selectionStart, this. selectionEnd);}); // IE8 or lower provides another solution: selection object, which belongs to document; // This object stores the text information selected by the user throughout the document; // compatible 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; // obtain the selected text of IE;} // PS: A problem exists: When IE triggers the select event, it is triggered immediately after a character is selected, in other browsers, the mouse is triggered when the desired character is selected and the mouse key is released; // If alert () is used, cross-browser incompatibility may occur; // so we can assign the selected text to another object; addEvent (textField, 'select', function () {// alert (getSelecText (this )); // inconsistent user behavior results; document. getElementById ('box '). innerHTML = getSelecText (this );})
3. filter input
// For the text box to enter the specified characters, 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 the character encoding; if (! /\ D/. test (String. formCharCode (charCode) & charCode> 9 &&! E. ctrlKey) {preDef (evt); // The condition prevents the default;}); // PS: the first half of the condition determines that only a number can be entered, resulting in regular buttons, for example, the cursor key, backspace key, and deletion key cannot be used. // Some browsers such as Firefox need to release these keys, and the encoding not triggered by characters is 0; // The browser before Safari3 will also be blocked, and its corresponding character encoding is all 8, so the judgment of charCode> 9 is added; // make sure that the user does not press the ctrl key;
// Prevents text box cropping, copying, and pasting. 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 crop operation occurs; beforepaste is triggered when a paste operation occurs; // if we want to disable cropping, copying, and pasting, the default behavior can be blocked. 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, that is: Input Method; // The Chinese input method. The principle is to store the text on the input method panel, press enter to write the English text, and press spaces to write the Chinese text; // solution: disable the calling of input methods through CSS; style = 'ime-mode: disabled '; // CSS is directly written; areaField. style. imeMode = 'Disabled '; // set in JS; // PS: Chrome cannot disable Input Method calling. Therefore, use regular expressions to verify the entered text. addEvent (areaField, 'keyup', function (evt) {this. value = this. value. replace (/[^ \ d]/g, ''); // replace all non-numbers with NULL ;});
4. automatic failover focus
// To increase the ease of use of form fields, when many fields meet certain conditions (such as the length), they are automatically switched to the next field to continue to fill in; <input type = 'text' name = 'user1' maxlength = '1'/> // only one can be written; <input type = 'text' name = 'user2' maxlength = '2'/> <input type = 'text' name = 'user3' maxlength = '3'/> function tabForward (evt) {var e = evt | window. event; var target = getTarget (evt); // determines 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 ++) {// locate the current field; if (fm. elements [I] = target) {// move the focus to the next field; if (fm. elements [I + 1]) {fm. elements [I + 1]. focus () ;}// return midway through; return ;}}}}
Three-choice box script
The selection box is created using the <select> and <option> elements;
HTMLSelectElement object
Attribute/method description
Add (new, rel) inserts a new element and specifies the position;
Boolean value of multiple, whether multiple choices are allowed;
Options <option> HTMLCollection set of elements;
Remove (index) removes the option at a given position;
SelectedIndex is based on the index of the selected item of 0. If no selected item is selected, the value is-1;
The number of lines visible in the size selection box;
// In the DOM, each <option> element has an HTMLOptionElement object to access data;
HTMLOptionElement object
Attribute description
Index the index of the current option in the options set;
The label of the current option;
Specifies whether the selected option is selected;
Text of the text option;
Value 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 select box may be select-one or select-multiple; // This depends on whether the multiple attribute exists in the HTML code; alert (city. options [0]. text); // Shanghai text, get the text value; alert (city. options [0]. value); // Shanghai value to obtain the value; // PS: it is best to use HTMLDOM for the select operation to ensure better browser compatibility; // if the standard DOM is used, different browsers will lead to different results; // PS: When the option does not have a value, IE will return an empty string, and other browsers will return a text value;
2. Select Options
The selectedIndex attribute is the easiest option to select only one option;
Copy codeThe Code is as follows:
AddEvent (city, 'change', function (){
Alert (this. selectedIndex); // obtain the index of the current option, starting from 0;
Alert (this. options [this. selectedIndex]. text); // obtain the text value of the current option;
Alert (this. options [this. selectedIndex]. value); // obtain the value of the current option;
});
City. selectedIndex = 1; // you can specify selectedIndex to locate an index;
You can use the option attribute selected (Boolean value) to locate an index and set it to true;
City. options [0]. selected = true; // you can specify the first index;
Differences between selected and selectedIndex:
1. selected is the returned Boolean value, so it is generally used to judge;
2. selectedIndex returns a value, which is generally used for setting and obtaining;
Copy codeThe Code is as follows:
AddEvent (city, 'change', function (){
If (this. options [2]. selected = true) {// checks whether the third option is selected;
Alert ('correct! ');
}
});
3. Add options
// If You Need To dynamically add options, we provide two solutions: DOM and Option constructor;
(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 has a bug;
(3). Use the add () method to add options:
Var option = new Option ('Beijing text', 'Beijing value ');
City. add (option, 0); // 0, indicating adding to the first place;
// PS: According to the DOM, the two parameters in add () are required. If the index is incorrect, the second parameter can be set to null, that is, it is moved to the last option by default;
// However, the second parameter in IE is optional. Therefore, setting null indicates that the parameter is placed in a non-existent location, leading to missing;
// For compatibility, undefined can be passed for compatibility;
City. add (option, null); // IE is not displayed;
City. add (option, undefined); // compatible;
4. Remove Option
// There are three ways to remove an option: DOM remove/remove () and null remove; city. removeChild (city. option [0]); // DOM removal; city. remove (0); // remove () remove, recommended; city. options [0] = null; // null remove; // PS: after the first item is removed, the following items are moved up, so the first item can be removed without stopping;
5. Move options
// If there are two selection boxes, move the first option in the first selection box to the second selection box, and the first option in the first selection box is removed; var city = fm. elements ['city']; // the first selection box; var info = fm. elements ['info']; // The second selection box; info. appendChild (city. options [0]); // move and delete it in the first selection box;
6. Arrange options
The selection box provides an index attribute to get the index value of the current option. The difference between the index value and selectedIndex is that one is the call of the Selection box object and the other is the call of the Option object;
Copy codeThe Code is as follows:
Var option1 = city. options [1];
City. insertBefore (option1, city. options [option1.index-1]); // shift up;
7. radio button
// Obtain the value of the single-choice button through the checked attribute; for (var I = 0; I <fm. sex. length; I ++) {// loop radio button; if (fm. sex [I]. checked = true) {// traverse each one to find the selected one; alert (fm. sex [I]. value); // get the value;} // PS: in addition to the checked attribute, the single-choice button also has a defacheckchecked button. // It gets the original checked button object, it will not change because of changes in the checked; if (fm. sex [I]. defaultChecked = true) {alert (fm. sex [I]. value );}
8. Check button
// Use the checked attribute to obtain 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 );