JavaScript text box scripting considerations _javascript Tips

Source: Internet
Author: User

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

One is the single line of text that uses the INPUT element, and the other is a multiline text box that uses textarea.

To use the input method, you must add the type and set it to "text."

    • size attribute, you can specify the number of characters that can be displayed within a text box.
    • value property to set the initial value of the text box.
    • maxlength attributes are used to specify the maximum number of characters that can be accepted within a text box.

The initial value of the textarea must be placed within the start and end tags.

    • cols is the text box character rows number;
    • rows is the number of text box character columns;

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

First, select the text

Both of these text boxes support

    • Select () method, which is used primarily to select all text in a text box. does not accept any parameters.
    • The Select event that corresponds to this method triggers the event when text in the text box is selected.

1. Select () method

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

var TextBox = document.getElementById ("MyForm"). elements["FirstName"];
Set default value
textbox.value = "Input your firstName";
Set event
Textbox.addeventlistener ("Focus", function () {
  event.target.select ();
});

2. Select Event

When this event is triggered:

    • In general, only the user selects the text (and the mouse is released) to trigger a select event;
    • In IE8 and earlier versions, a select event is triggered whenever a user chooses a letter (without releasing the mouse);
    • is also triggered when the Select () method is invoked;

Such as:

var TextBox = document.getElementById ("MyForm"). elements["FirstName"];
Set default value
textbox.value = "Input your firstName";
Sets the event
textbox.addeventlistener ("select", Function () {
  console.log ("selected");
});

3, get the selected text

Take advantage of two properties:

    • SelectionStart
    • Selectionend

These two properties hold a numeric value based on 0 that represents the range (offset) of the selected text. So to get the text in the text box that the user chooses, you can use the following code:

var TextBox = document.getElementById ("MyForm"). elements["FirstName"];
Set default value
textbox.value = "Input your firstName";
Sets the event
textbox.addeventlistener ("select", Function () {
  var selected = textBox.value.substring ( Textbox.selectionstart,textbox.selectionend);
  Console.log (selected); 
});

Alternatively, you can use this property to set the default full selection 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, when using the Selectionstart/end property, IE8 does not support it, but supports another named

    • Document.selection object that holds the text information selected by the user throughout the document range

Gets the compatible version of the selected text as:

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 part of the text

The way to select some text is:

Setselectionrange () method . Receive two parameters: the index of the first character to be selected and the index of the last character.
such as blocking user selection:

Textbox.addeventlistener ("Focus", function () {
  textbox.setselectionrange (0,0);
});
Textbox.addeventlistener ("Select", Function () {
  textbox.setselectionrange (0,0);
});

Set focus to the text box immediately before or after calling Setselectionrange (). And the way used in IE is the scope to solve the problem of text:

var range = Textbox.createtextrange ();
Range.collapse (TRUE); The range is folded to the opening
Range.movestart ("Character", 0);
Range.moveend ("Character", textBox.value.length);
Range.Select ();

Compatible version: more commonly used

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 opening
    Range.movestart ("Character", StartIndex);
    Range.moveend ("Character", Stopindex);
    Range.Select ();}
  ;

Third, filter input

1, shielding characters

The following code allows only numbers to be entered:

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 on the up, down, and backspace keys, so it is necessary to unblock these commonly used operation keys as long as they do not block keys that are less than 10 characters encoded:

Textbox.addeventlistener ("KeyPress", function () {
  if (!/\d/.test (String.fromCharCode (Event.charcode)) & & Event.charcode > 9 &&!event.ctrlkey) {//Enter only digital
    event.preventdefault ();};}
);

Iv. operation of Clipboard

Here are 6 clipboard events

    • Beforecopy: Triggered before a copy operation occurs
    • Copy: Triggered when replication occurs
    • Beforecut: Action before clipping occurs
    • Cut: action when pasting occurs
    • Beforepaste: Trigger before pasting action occurs
    • Paste: triggered when a sticky action occurs

If you set a prohibit copy:

Copy
Textbox.addeventlistener ("Beforecopy", function () {
  Textbox.value = "Do not copy";
})
before copying; Copies
are prohibited from copying Textbox.addeventlistener ("Copy", function () {
  event.preventdefault ();
});

To access the data in the Clipboard, you can use the Clipboarddata object, which is the property of the Window object in IE, Friefox,safari and chrome, which is the property of the corresponding event object; You can access the object at any time in IE , but only valid during Clipboard events in other browsers.

This Clipboarddata object has three methods:

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

GetData () receives a parameter, which is the format of the data (ie has two data formats: text and URL; in other browsers, this parameter is a MIME type; however, you can use text instead of Text/plain).

SetData () receives two parameters, namely the data type and the text to be placed on the Clipboard. (in the first argument, IE supports text and URLs; In the second argument Chrome and Safari do not support text types); Both browsers return true if the text is successfully placed on the Clipboard, otherwise, returns false:

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);
  }


The browser is now gradually tightening its operations on accessing the Clipboard.

Five, automatic switching focus

The theory is to automatically switch the focus to the next text box after the maximum number of characters in the previous text box is played:

Dom:

<form action= "" >
  <input type= "text" name= "Tel11" id= "TxtTel1" maxlength= "3" >
  <input type= " Text "Name=" tel12 "id=" TxtTel2 "maxlength=" 3 ">
  <input type=" text "name=" Tel13 "id=" TxtTel3 "maxlength=" 4 " >
  <input type= "Submit" Name= "BTN" id= "BTN" value= "Submit" >
</form>

Js:

 var textbox1 = document.getElementById ("TxtTel1"); var textbox2 = document.getElementById
("TxtTel2");

var TextBox3 = document.getElementById ("TxtTel3");
Textbox1.addeventlistener ("KeyUp", Tabforward);
Textbox2.addeventlistener ("KeyUp", Tabforward);

Textbox3.addeventlistener ("KeyUp", Tabforward);
  function Tabforward () {var target = Event.target;
    When the value length equals the maximum value, if (target.value.length = = target.maxlength) {var form = Target.form; Iterate through the elements of the form form that is in the for (var i = 0, len = form.elements.length i < len; i++) {//If the element is the target element if (Form.ele Ments[i] = = target) {//and the next element of the element is true other conditions if ((Form.elements[i + 1]) && (form.elements[i + 1).  NodeType = = 1 && (form.elements[i + 1].tagname.tolowercase () = "input") && (form.elements[i + 1].type =
        "Text") {//The next element gets focus Form.elements[i + 1].focus ();
  }
      }
    }; }
}

VI. HTML5 constraint Validation API

1, required fields required properties

Adds a property required to a required field. It applies to input,textarea,select fields. Use the following code to detect whether the browser supports required properties:

var isrequiredsupported= "required" in document.createelement ("input");

2. Other input types

The type attribute of input adds "email" and "url", and each browser adds a custom validation mechanism to them:

var input = document.createelement ("input");
Input.type = "email";
var isemailsupported = (Input.type = = "email");

3. Numerical Range

In addition to "email" and "URL", HTML5 also defines several additional input elements. These elements require a numeric based value: "Number", "Range", "datetime", "datetime-local", "date", "Mouth", "Week", "Time". Currently browsers are not good for these types of support, and be careful if you really want to use them.

Yes, that's right. The input element of a numeric type can specify the min attribute, the max attribute, and the step property. There are also two methods for these numeric type elements: Stepup (), Stepdown (). Accepts a parameter, the value to be added or subtracted from the current base.

Dom:

<form action= "" >
  <input type= "range" name= "Tel14" id= "TxtTel4" required "min=" max= "" step= "1" >
  <input type= "button" value= "Up" id= "up" >
  <input type= "text" id= "Output" >
  <input type= " Submit "Name=" BTN "id=" BTN "value=" Submit ">
</form>

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 () {
  //click value to increase by 2
  input.stepup (2);
  var output = document.getElementById ("output");
  Output.value = Input.value;
});

3. Input mode

HTML5 adds the Pattern property, which is a regular expression that matches the value in the text box.

<input type= "text" id= "number" pattern= "\d{3}" >

var num = document.getElementById ("number");
Console.log (Num.pattern); \D{3}

You can use the following code to detect whether the browser supports pattern attributes:

var ispatternsupported= "pattern" in document.createelement ("input");

4. Detection effectiveness

Use the Checkvalidity () method to detect whether the fields in the form are valid. All form fields have this method, and if the check is valid returns True.

<form action= "" >
  <input type= "text" pattern= "W" id= "name" required> <input type=
  "number" max= " "id=" num "required>
  <input type=" button "id=" Check "value=" Check ">
  <input type=" Submit "id=" Submit "value=" Submit "disabled>
</form>

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 ());//check that the entire form is correct
  if ( Form.checkvalidity ()) {
    Submit.removeattribute ("Disabled");
    Check.disabled = true;
  } else{
    alert ("Please check the form");
  }
);

The validity property of input gives specific information about what fields are valid and invalid.

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 to set the setcustomvalidity ();
    • Patternmismatch: Whether it matches the pattern attribute;
    • Rangeoverflow: is larger than Max value;
    • Rangeunderflow: is smaller than min value;
    • Stepmismatch: Whether the step is reasonable;
    • Toolong: Whether more than the maxlength;
    • Typemismatch: Is not a mail type and URL type;
    • Valid: Returns True if all the other properties here are false;
    • Valuemissing: Returns True if there is no value in the required.

5. Disable authentication

By setting the Novalidate property of a form, you can be a form that is not validated. When you get a form with JS, setting its Novalidate property to true disables form validation.

Adding the Formnovalidate property on the Submit button will not validate the submit form. When you get the Submit button with JS, setting its Formnovalidata property to true disables form validation and commits.
The above is the entire content of this article, I hope to help you learn.

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.