Notes for writing JavaScript text box scripts _ javascript skills

Source: Internet
Author: User
This article mainly introduces considerations for writing JavaScript text box scripts and helps you better compile javascript form scripts. For more information, see in HTML, there are two ways to express the text box:

One is a single line text that uses the input element, and the other is a multi-line text box that uses textarea.

When using the input method, you must add type and set it to "text ".

  • SizeFeature, you can specify the number of characters that can be displayed in the text box.
  • ValueAttribute to set the initial value of the text box.
  • MaxlengthIt is used to specify the maximum number of characters that can be accepted in the text box.

The initial value of textarea must be placed in the start and end labels.

  • ColsIs the number of characters in the text box;
  • RowsIs the number of character columns in the text box;

In addition, you cannot specify the maximum number of characters for textarea in HTML;

1. Select text

Both of the preceding text boxes are supported.

  • Select () method, which is mainly used to select all text in the text box. No parameters are accepted.
  • The select event corresponding to this method is triggered by a text event in the selected text box.

1. select () method

The following code Selects all texts as long as the text box gets the focus:

Var textBox = document. getElementById ("myForm "). elements ["firstName"]; // sets the default value textBox. value = "input your firstName"; // you can specify the event textBox. addEventListener ("focus", function () {event.tar get. select ();});

2. select event

When to trigger this event:

  • Generally, a select event is triggered only when the user selects the text (and the mouse must be released;
  • In IE8 and earlier versions, a select event is triggered if you select a letter (without having to release the mouse;
  • It is also triggered when the select () method is called;

For example:

Var textBox = document. getElementById ("myForm "). elements ["firstName"]; // sets the default value textBox. value = "input your firstName"; // you can specify the event textBox. addEventListener ("select", function () {console. log ("selected ");});

3. Obtain the selected text

Use two attributes:

  • SelectionStart
  • SelectionEnd

These two attributes are saved based on a value of 0, indicating the range (offset) of the selected text ). To obtain the text in the text box selected by the user, use the following code:

Var textBox = document. getElementById ("myForm "). elements ["firstName"]; // sets the default value textBox. value = "input your firstName"; // you can specify the event textBox. addEventListener ("select", function () {var selected = textBox. value. substring (textBox. selectionStart, textBox. selectionEnd); console. log (selected );});

In addition, you can also use this attribute to set the default all-selected status when the focus is obtained:

textBox.addEventListener("focus", function () {  textBox.selectionStart = "0";  textBox.selectionEnd = textBox.value.length;});

Or:

textBox.addEventListener("focus", function () {  textBox.blur();});

However, IE8 does not support the selectionStart/End attribute

  • Document. selection object, which stores the text information selected by the user throughout the document

Obtain the compatible version of the selected text:

function getSelectedText (textbox) {  if (typeof textbox.selectionStart == "number") {    return textbox.value.substring(textbox.selectionStart,textbox.selectionEnd);  }else if (document.selection) {    return document.selection.createRange().text;  }}

Ii. Select some text

You can select some text by using the following methods:

SetSelectionRange () method. Two parameters are received: the index of the first character and the index of the last character.
To prevent users from choosing:

textBox.addEventListener("focus", function () {  textBox.setSelectionRange(0,0);});textBox.addEventListener("select", function () {  textBox.setSelectionRange(0,0);});

Set the focus to the text box immediately before or after calling setSelectionRange. The method used in IE is applicable to solve the text problem:

Var range = textBox. createTextRange (); range. collapse (true); // The range is folded to the starting range. moveStart ("Character", 0); range. moveEnd ("Character", textBox. value. length); range. select ();

Compatible versions: Common

Function selectText (textbox, startIndex, stopIndex) {if (textbox. setSelectionRange) {textbox. setSelectionRange (startIndex, stopIndex);} else if (textbox. createTextRange () {var range = textbox. createTextRange (); range. collapse (true); // The range is folded to the starting range. moveStart ("Character", startIndex); range. moveEnd ("Character", stopIndex); range. select ();};}

Iii. filter input

1. Blocked characters

The following code allows only numbers:

Var textBox = document. getElementById ("myForm"). elements ["firstName"]; textBox. autofocus = true; textBox. addEventListener ("keypress", function () {if (! /\ D/. test (String. fromCharCode (event. charCode) {// enter only the number event. preventDefault ();};});

However, some browsers will trigger the keypress event for the up, down, and back keys, so you need to cancel the prohibition on these commonly used Operation Keys, as long as you do not shield those keys with character encoding less than 10:

TextBox. addEventListener ("keypress", function () {if (! /\ D/. test (String. fromCharCode (event. charCode) & event. charCode> 9 &&! Event. ctrlKey) {// only enter the number event. preventDefault ();};});

4. Operate the clipboard

The following are 6 clipboard events:

  • Beforecopy: triggered before a replication operation
  • Copy: triggered when replication occurs.
  • Beforecut: operation before Cropping
  • Cut: operation when a post is added
  • Beforepaste: triggered before pasting
  • Paste: triggered when a pasting operation occurs

For example, disable copy:

// A message is displayed, indicating that textBox cannot be copied. addEventListener ("beforecopy", function () {textBox. value = "do not copy" ;}); // textBox cannot be copied during copy. addEventListener ("copy", function () {event. preventDefault ();});

To access the data in the clipboard, you can use the clipboardData object. In IE, this object is the property of the window object. In friefox, safari, and chrome, this object is the property of the corresponding event object; this object can be accessed at any time in IE, but it is valid only in other browsers during clipboard event processing.

This clipboardData object has three methods:

  • GetData ()
  • SetData ()
  • ClearData ()

GetData () receives a parameter, that is, the format of the data to be obtained (IE has two data formats: text and URL; in other browsers, this parameter is a MIME type; however, text can be used instead of text/plain ).

SetData () receives two parameters: Data Type and text to be placed on the clipboard. (IE supports text and URL in the first parameter; chrome and safari do not support text in the second parameter); after the two browsers successfully put the text in the clipboard, true is returned; otherwise, false is returned:

function getClipboardText(event) {  var clipboardData = (event.clipboardData || window.clipboardData);  return clipboardData.getData("text");}function setClipboardText(event, value) {  if (event.clipboardData) {    return event.clipboardData.setData("text/plain", value);  } else if (window.clipboardData) {    return window.clipboardData.setData("text", value);  }}

Currently, the browser is tightening its access to the clipboard.

V. automatic failover focus

Theoretically, after the characters in the previous text box reach the maximum number, the focus is automatically switched to the next text box:

DOM:

 

Js:

Var textbox1 = document. getElementById ("txtTel1"); var textbox2 = document. getElementById ("txtTel2"); var textbox3 = document. getElementById ("txtTel3"); textbox1.addEventListener ("keyup", tabForward); textbox2.addEventListener ("keyup", tabForward); encrypt ("keyup", tabForward); function tabForward () {var target = event.tar get; // if (target. value. length = target. maxLength) {var form = target. form; // traverses the element for (var I = 0, len = form. elements. length; I <len; I ++) {// if this element is a target element if (form. elements [I] = target) {// and the next element of this element is true. elements [I + 1]) & (form. elements [I + 1]. nodeType = 1) & (form. elements [I + 1]. tagName. toLowerCase () = "input") & (form. elements [I + 1]. type = "text") {// obtain the focus form for the next element. elements [I + 1]. focus ();}}};}}

6. HTML5 constraint verification API

1. required field required attribute

Add the required attribute to the required field. It applies to input, textarea, and select fields. Use the following code to check whether the browser supports the required attribute:

var isRequiredSupported="required" in document.createElement("input");

2. Other input types

"Email" and "url" are added to the type attribute of input. Each browser also adds a custom verification mechanism for them:

var input = document.createElement("input");input.type = "email";var isEmailSupported = (input.type == "email");

3. Value Range

In addition to "email" and "URL", HTML5 also defines several other input elements. All these elements must be numeric-based values: "number", "range", "datetime", "datetime-local", "date", "mouth ", "week", "time ". Currently, browsers do not support these types well. If you really want to use them, be careful.

You can specify the min attribute, max attribute, and step attribute for the input element of the numeric type. At the same time, there are two methods for these value types: stepUp () and stepDown (). Both accept a parameter and add or subtract a value to the current base.

DOM:

 

Js:

Var input = document. getElementById ("txtTel4"); var up = document. getElementById ("up"); input. addEventListener ("mousemove", function () {var output = document. getElementById ("output"); output. value = input. value;}); up. addEventListener ("click", function () {// The value of the clicked value is increased in 2 units. stepUp (2); var output = document. getElementById ("output"); output. value = input. value ;});

3. input mode

HTML5 adds the pattern attribute. The value of this attribute is a regular expression used to match the value in the text box.

var num = document.getElementById("number");console.log(num.pattern); //\d{3}

Use the following code to check whether the browser supports the pattern attribute:

var isPatternSupported="pattern" in document.createElement("input");

4. Check Validity

The checkValidity () method can be used to check whether the fields in the form are valid. All fields in the form have this method. If this method is valid, true is returned.

Var form = document. forms [0]; var name = document. getElementById ("name"); var number = document. getElementById ("num"); var check = document. getElementById ("check"); var submit = document. getElementById ("submit"); check. addEventListener ("click", function () {console. log (form. checkValidity (); // checks whether the entire form is correct if (form. checkValidity () {submit. removeAttribute ("disabled"); check. disabled = true;} else {alert ("Please check the form ");}});

The validity attribute of input provides the valid and invalid fields.

Var inputName = document. getElementById ("inputName"); inputName. onblur = function () {if (inputName. checkValidity () {inputName. style. color = "white"; inputName. style. backgroundColor = "green";} else {inputName. style. color = "white"; inputName. style. backgroundColor = "red"; if (inputName. validity. patternMismatch) {inputName. value = "please fill in the correct format" ;}}}; inputName. addEventListener ("mouseenter", function () {inputName. focus (); inputName. select ();});

Validity mainly includes the following attributes:

  • CustomError: whether setCustomValidity () is set ();
  • PatternMismatch: whether it matches the pattern attribute;
  • RangeOverflow: greater than the max value;
  • RangeUnderflow: whether the value is smaller than min;
  • StepMisMatch: whether the step size is reasonable;
  • TooLong: whether maxlength is exceeded;
  • TypeMismatch: whether it is not the mail type or url type;
  • Valid: if all other attributes here are false, true is returned;
  • ValueMissing: If the value is not in required, true is returned.

5. Disable Verification

By setting the novalidate attribute of the form, it can be that the form is not verified. After obtaining a form using js, setting the novalidate attribute to true will disable form verification.

Adding the formnovalidate attribute on the submit button does not validate the submission form. After you use js to obtain the submit button, set its formnovalidata attribute to true, and disable Form Verification and submit.
The above is all the content of this article, hoping 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.