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 initial value of textarea must be placed within the start and end tags.
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
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:
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:
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
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个剪贴板事件
如设置禁止拷贝:
//拷贝之前提示禁止拷贝 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()接收一个参数,即要取得数据的格式(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主要包括下列屬性:
5、停用驗證
透過設定表單的novalidate屬性,可以是表單不進行驗證。用js取得form之後,設定它的novalidate屬性為true,會停用表單驗證。
在提交按鈕上新增formnovalidate屬性,會不驗證提交表單。用js取得submit按鈕之後,設定它的formnovalidata屬性為true,會停用表單驗證並提交。
以上就是本文的全部內容,希望對大家的學習有所幫助。