search
HomeWeb Front-endJS TutorialThings to note when writing JavaScript text box scripts_javascript tips

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

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

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

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

or:

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

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

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

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

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

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

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

四、操作剪贴板

以下是6个剪贴板事件

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

如设置禁止拷贝:

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

要访问剪贴板中的数据,可以使用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);
  }
}

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

五、自动切换焦点

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

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;
  //当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();
        }
      }
    };
  }
}

六、HTML5约束验证API

1、必填字段required属性

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

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

2、其他输入类型

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

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

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>

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

3、输入模式

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

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

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

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

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

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("请检查表单");
  }
});

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

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.

Statement
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.