Home > Web Front-end > JS Tutorial > Things to note when writing JavaScript text box scripts_javascript tips

Things to note when writing JavaScript text box scripts_javascript tips

WBOY
Release: 2016-05-16 15:18:32
Original
1391 people have browsed it

In HTML, there are two ways to represent text boxes:

One is a single line of text using input elements, and the other is a multi-line text box using textarea.

To use the input method, type must be added and set to "text".

    The
  • size property allows you to specify the number of characters that can be displayed in the text box.
  • The
  • value attribute can set the initial value of the text box.
  • The
  • maxlength attribute 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 within the start and end tags.

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

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

1. Select text

Both of the above text boxes are supported

  • select() method, this method is mainly used to select all text in the text box. Does not accept any parameters.
  • The select event corresponding to this method is triggered when the text in the text box is selected.

1. select() method

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

var textBox = document.getElementById("myForm").elements["firstName"];
//设置默认值
textBox.value = "input your firstName";
//设置事件
textBox.addEventListener("focus", function () {
  event.target.select();
});
Copy after login

2. select event

When this event is triggered:

  • Generally, the select event will be triggered only when the user selects text (and releases the mouse);
  • In IE8 and earlier versions, as long as the user selects a letter (without releasing the mouse), the select event will be triggered;
  • will also be triggered when the select() method is called;

For example:

var textBox = document.getElementById("myForm").elements["firstName"];
//设置默认值
textBox.value = "input your firstName";
//设置事件
textBox.addEventListener("select", function () {
  console.log("selected");
});
Copy after login

3. Get the selected text

Use of two attributes:

  • selectionStart
  • selectionEnd

These two attributes store 0-based values, indicating the range (offset) of the selected text. Therefore, to get the text in the text box selected by the user, you can use the following code:

var textBox = document.getElementById("myForm").elements["firstName"];
//设置默认值
textBox.value = "input your firstName";
//设置事件
textBox.addEventListener("select", function () {
  var selected = textBox.value.substring(textBox.selectionStart,textBox.selectionEnd);
  console.log(selected); 
});
Copy after login

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

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

or:

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

However, when using the selectionStart/End attributes, IE8 does not support it, but supports another one named

  • document.selection object, which stores the text information selected by the user within the entire document

Get 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;
  }
}
Copy after login

2. Select part of the text

The method to select part of the text is:

setSelectionRange() method . Receives two parameters: the index of the first character to be selected and the index of the last character.
To block user selection:

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

To set focus to the text box immediately before or after calling setSelectionRange(). The method used in IE is the scope of application to solve text problems:

var range = textBox.createTextRange();
range.collapse(true); //范围折叠到开头
range.moveStart("Character",0);
range.moveEnd("Character",textBox.value.length);
range.select();
Copy after login

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); //范围折叠到开头
    range.moveStart("Character", startIndex);
    range.moveEnd("Character", stopIndex);
    range.select();
  };
}
Copy after login

3. Filter input

1. Block characters

The following code only allows entering numbers:

var textBox = document.getElementById("myForm").elements["firstName"];
textBox.autofocus = true;
textBox.addEventListener("keypress", function () {
  if (!/\d/.test(String.fromCharCode(event.charCode))) { //仅输入数字
    event.preventDefault();
  };
});
Copy after login

However, some browsers will trigger keypress events for the up, down, and backspace keys, so you need to unban these commonly used operation keys, as long as you do not block those keys whose character encoding is less than 10:

textBox.addEventListener("keypress", function () {
  if (!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9 && !event.ctrlKey) { //仅输入数字
    event.preventDefault();
  };
});
Copy after login

四、操作剪贴板

以下是6个剪贴板事件

  • beforecopy:在发生复制操作前触发
  • copy:在发生复制时触发
  • beforecut:在发生剪贴前操作
  • cut:在发生加贴时操作
  • beforepaste:在发生黏贴操作前触发
  • paste:在发生黏贴操作时触发

如设置禁止拷贝:

//拷贝之前提示禁止拷贝
textBox.addEventListener("beforecopy", function() {
  textBox.value = "do not copy";
});
//拷贝时禁止拷贝
textBox.addEventListener("copy", function() {
  event.preventDefault();
});
Copy after login

要访问剪贴板中的数据,可以使用clipboardData对象,在IE中,这个对象是window对象的属性,在friefox,safari和chrome,这个对象是相应event对象的属性;在IE中可以随时访问该对象;但在其他浏览器中只有在处理剪贴板事件期间才有效。

这个clipboardData对象有三个方法:

  • getData()
  • setData()
  • clearData()

getData()接收一个参数,即要取得数据的格式(IE中有两种数据格式:text和URL;在其他浏览器中这个参数是一种MIME类型;不过可以用text代替text/plain)。

setData()接收两个参数,即数据类型和要放在剪贴板中的文本。(第一个参数中,IE支持text和URL;第二个参数中chrome和safari不支持text类型);这两个浏览器在成功将文本放到剪贴板中后,都会返回true;否则,返回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);
  }
}

Copy after login

目前浏览器逐渐收紧对访问剪贴板的操作。

五、自动切换焦点

理论上就是在前一个文本框中的字符打到最大数量后,自动将焦点切换到下一个文本框:

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>
Copy after login

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;
  //当value长度等于最大值的时候
  if (target.value.length == target.maxLength) {
    var form = target.form;
    //遍历所在的form表单中的元素
    for (var i = 0, len = form.elements.length; i < len; i++) {
      //如果该元素是目标元素
      if (form.elements[i] == target) {
        //并且该元素的下一个元素为true 其他条件
        if ((form.elements[i + 1]) && (form.elements[i + 1].nodeType == 1) && (form.elements[i + 1].tagName.toLowerCase() == "input") && (form.elements[i + 1].type == "text")) {
          //则下个元素获得焦点
          form.elements[i + 1].focus();
        }
      }
    };
  }
}

Copy after login

六、HTML5约束验证API

1、必填字段required属性

在必填字段中添加属性required。它适用于input,textarea,select字段。使用下面的代码可以检测浏览器是否支持required属性:

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

2、其他输入类型

input的type属性增加了“email”和“url”;各浏览器也都为它们增加了定制的验证机制:

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

3、数值范围

除了“email”和“URL”,HTML5还定义了另外几个输入元素。这几个元素都要求填写基于数字的值:“number”,“range”,“datetime”,“datetime-local”,“date”,“mouth”,“week”,“time”。目前浏览器对这些类型支持并不好,如果真想使用的话要小心。

对这事数值类型的输入元素可以指定min属性,max属性,step属性。同时这些数值类型元素还有两个方法:stepUp(),stepDown()。都接受一个参数,要在当前基础上加上或减去的数值。

DOM:

<form action="">
  <input type="range" name="tel14" id="txtTel4" required min="10" max="20" step="1">
  <input type="button" value="up" id="up">
  <input type="text" id="output">
  <input type="submit" name="btn" id="btn" value="submit">
</form>
Copy after login

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 () {
  //点击value值以2为单位增加
  input.stepUp(2);
  var output = document.getElementById("output");
  output.value = input.value;
});

Copy after login

3、输入模式

HTML5新增了pattern属性,这个属性的值是一个正则表达式,用于匹配文本框中的值。

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

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

Copy after login

可以使用以下代码来检测浏览器是否支持pattern属性:

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

4、检测有效性

使用checkValidity()方法可以检测表单中的字段是否有效。所有表单的字段都有这个方法,如果检查有效返回true。

<form action="">
  <input type="text" pattern="w" id="name" required>
  <input type="number" max="10" 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()); //检测整个表单是否正确
  if (form.checkValidity()) {
    submit.removeAttribute("disabled");
    check.disabled = true;
  }else{
    alert("请检查表单");
  }
});

Copy after login

input的validity属性会给出什么字段有效和无效的具体信息。

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 = "请填写正确的格式";
    }
  }
};
inputName.addEventListener("mouseenter", function () {
  inputName.focus();
  inputName.select();
});

Copy after login

Validity mainly includes the following attributes:

  • customError: whether setCustomValidity() is set;
  • patternMismatch: whether it matches the pattern attribute;
  • rangeOverflow: whether it is larger than the max value;
  • rangeUnderflow: whether it is smaller than the min value;
  • stepMisMatch: whether the step size is reasonable;
  • tooLong: whether maxlength is exceeded;
  • typeMismatch: whether it is not the mail type and url type;
  • valid: If other attributes here are false, return true;
  • valueMissing: If there is no value in required, return true.

5. Disable verification

By setting the novalidate attribute of the form, the form can not be verified. After obtaining the form using js, setting its novalidate attribute to true will disable form validation.

Adding the formnovalidate attribute to the submit button will not validate the submitted form. After using js to get the submit button, set its formnovalidata attribute to true, which will disable form validation and submit it.
The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template