Introduction to JavaScript form scripts
When people first started using JavaScript, one of the main purposes was to verify the form and share the responsibility of the server for processing the form. Although most of the popular submission methods are through ajax, understanding the form is also of great help to the ajax method! Therefore, please do not underestimate the form.
1. Basic knowledge of forms
In HTML, forms are represented by elements, while in JavaScript, forms correspond to the HTMLFormElement type.
Attributes and methods of table HTMLFormElement
Attributes or methods | Function description |
---|---|
acceptCharset | The character set that the server can handle; equivalent to the accept-charset feature in HTML |
action | Receive the requested URL; equivalent to the action attribute in HTML |
elements | A collection of all controls in the form (HTMLCollection) |
enctype | The requested encoding type; equivalent to the enctype attribute in HTML |
length | The number of controls in the form |
method | The type of HTTP request to be sent; equivalent to the method attribute of HTML |
name | The name of the form; equivalent to the name attribute of HTML |
reset() | Reset all form fields to their default values |
submit() | Submit form |
target | The name of the window used to send requests and receive responses; equivalent to HTML target properties |
1. Get the <form>
element
Method 1: through getElementById(element id)
var form = document.getElementById("form1");1
Method 2: Get all forms on the page through document.forms , and then get the corresponding form through the numerical index
var firstForm = document.forms[0];1
Method 3: Get all the forms on the page through document.forms, and then get the corresponding form by the form name in the page
var myForm = document.forms["form2"];1
Method 4: Early browsers will Save each form with the name attribute set as an attribute in the document object [It is recommended not to use this method]
var myFormf = document.form2;1
2. Submit the form
(1) Submit button submission
method 1: Universal submit button
<input type="submit" value="Submit Form" />1
Method 2: Customized submit button
<button type="submit">Submit Form</button>1
Method 3: Image button
<input type="image" value="submitBtn.gif" />1
As long as any of the buttons listed above exists in the form , then when the corresponding form control has focus, you can submit the form by pressing the Enter key. (Except textarea. Entering a carriage return in the text area will cause a new line). If the form does not have a submit button, pressing the Enter key will not submit the form.
Note, by submitting the form through the above method, the browser will trigger the submit event before sending the request to the server.
This way you can decide whether you need to validate the form. Blocking the default behavior of this event will cancel the form submission.
<form action="http://www.baidu.com"> <input id="name"/> <button type="submit">Submit Form</button></form><script type="text/javascript"> var form = document.forms[0]; form.addEventListener("submit", function(event) { var name = document.getElementById("name"); if(name.value === "") { event.preventDefault(); } });</script>12345678910111213
Additional: If you want to disable form submission via carriage return, please refer to [HTML to prevent form submission by entering carriage return]
(2) Submit in JavaScript
var form = document.forms[0];form.submit();12
Note, this method will not trigger the sumbit event.
The biggest problem that may occur when submitting a form is submitting the form repeatedly.
Solution:
(1) Disable the submit button after submitting the form for the first time.
To be processed in the "submit" event handling function, it cannot be processed in the "click" event handling function. Because some browsers will trigger the submit event before the click event is triggered!
(2) Use the onsubmit event handler to cancel subsequent form submission methods.
In our project, requests are submitted through ajax, and the method of preventing repeated submissions is roughly similar to the above (2). Intercept the ajax before sending, the sending is successful, and the sending is completed. Use the state machine to identify the current state (loading, resubmit, success, error). When the user requests ajax, we determine which state it is currently in:
If the initial state is null, the request is sent directly and the state is switched to loading;
If it is loading or resubmit, it will prompt "The request is being processed, do not repeat the request" and switch the status to resubmit;
If it is success or error, it will prompt "Success or Failed", and then changes to the initial state.
3. Reset form
(1)Reset button submission
Method 1: Universal reset button
<input type="reset" value="Reset Form" />1
Method 2: Custom reset button
<button type="reset">Reset Form</button>1
Note, by resetting the form in the above way, the browser will trigger the reset event. Blocking the default behavior of this event will cancel the reset submission.
<form action="http://www.php.cn"> <input id="name"/> <button type="submit">Submit Form</button> <button type="reset"> Reset Form</button> </form> <script type="text/javascript"> var form = document.forms[0]; form.addEventListener("reset", function(event) { alert("我就不让你重置,咋地!"); event.preventDefault(); })</script>123456789101112
(2) Reset in JavaScript
var form = document.forms[0];form.reset();12
Note, this method will not trigger the reset event.
4. Form field
form.elements, obtains the collection of all controls in the form (HTMLCollection).
form.elements[n]; // Return the n+1th element
form.elements["name"]; / / Return the NodeList
<form action=" <input id="name" name="name"/> <input type="radio" name="color" value="red"/>Red <input type="radio" name="color" value="green"/>Green <input type="radio" name="color" value="blue"/>Blue <button type="submit">Submit Form</button> <button type="reset"> Reset Form</button> </form> <script type="text/javascript">var form = document.forms[0]; form.elements[1] === form.elements["color"][0];// value值为red的input标签</script>123456789101112
whose name value is "name" (1) Form field attribute
Attribute | Function Description |
---|---|
disabled | Boolean value, indicating whether the current field is disabled |
form | Pointer to the form to which the current field belongs; read-only |
name | The name of the current field |
readOnly | Boolean value, indicating whether the current field is read-only |
tabIndex | Indicates the switching (tab) sequence number of the current field |
type | The type of the current field |
value | The value of the current field being submitted to the server. For file fields, this attribute is read-only and contains the path of the file on the computer |
(2)表单字段方法
foucs()获取焦点,激活字段,使其可以响应键盘事件
blur()失去交单。
window.addEventListener("load", function() { document.forms[0].elements[0].focus(); // 让表单第一个元素获取焦点});123
HTML5中表单字段新增了autofoucs属性。
<input type="text" autofoucs />1
(3)表单字段事件
blur:当前字段失去焦点触发
change:对于和元素,在它们失去焦点且value值改变时触发;对于元素,在其选项改变时触发。
focus:当前字段获取焦点时触发
表单错误提示流程:利用focus事件修改文本框的背景颜色,以便清楚表明这个字段获取了焦点;利用blur事件恢复文本框的背景颜色;利用change事件在用户输入了非规定字符时提示错误。
在项目中的validate插件,只用到了blur和focus事件。因为某些浏览器中,blur事件会先于change事件;有些会恰好相反!
二、文本框脚本
HTML中,有两种方式表示文本框:单行文本框<input type="text">
、多行文本框<textarea>
。
(1)单行文本框
通过设置size特性,可以指定文本框中能够显示的字符数;通过设置value特性,可以指定文本框的初始值;通过设置maxlength特性,可以指定文本框可以接受的最大字符数。
<!-- 显示5个字符(input 元素的宽度),输入不能超过10个字符--><input type="text" value="初始值放到这里" size="5" maxlength="10"/>12
(2)多行文本框
rows设置文本框行数,cols设置文本框列数。
<textarea cols="10" rows="5">初始值必须放在这里</textarea>1
上述两种文本框,都会将用户输入的内容保存在value属性中!!!
1. 选择文本
(1)选择(select)事件
选择文本框中所有文本select()方法,对应的是一个select事件,同样存在触发时间的问题!
var input = document.getElementById("name"); input.addEventListener("focus", function(event) { event.target.select(); });1234
(2)取得选择的文本
var textarea = document.getElementById("content");textarea.addEventListener("select", function(event) { if(typeof textarea.selectionStart === "number") { console.log(textarea.value.substring(textarea.selectionStart, textarea.selectionEnd));}else if(document.selection){ // IE下 console.log(document.selection.createRange().text);} });123456789
(3)选择部分文本
setSelectionRange(要选择的第一个字符索引, 要选择的最后一个字符索引)
注意要看到被选择的文本,必须在调用setSelectionRange()之前或之后立即将焦点设置到文本框。
function selectText(textbox, startIndex, endIndex) { if(textbox.setSelectionRange) { textbox.setSelectionRange(startIndex, endIndex); } else if(textbox.createTextRange) { var range = textbox.createTextRange(); range.collapse(true); range.moveStart("character", startIndex); range.moveEnd("character", endIndex - startIndex); range.select(); } // 将焦点设置到文本框上 textbox.focus(); }12345678910111213
部分选择文本的技术在实现高级文本输入框时很有用,例如提供自动完成建议的文本框就可以使用这种技术。
2. 过滤输入
(1)屏蔽字符
当需要用于输入的文本中不能包含某些字符时,例如手机号,只能输入字符!
var input = document.getElementById("name"); input.addEventListener("keypress", function(event) { if(!/\d/.test(String.fromCharCode(event.charCode)) && event.charCode > 9 && !event.ctrlKey) { // 只允许输入数字和退格特殊键以及Ctrl event.preventDefault(); } });1234567
更极端的方式,可以通过event.preventDefault();阻止其默认行为来禁止按键操作,即文本框只读!!
(2)操作剪贴板
var EventUtil = { getClipboardText: function(event){ var clipboardData = (event.clipboardData || window.clipboardData); // 兼容IE return clipboardData.getData("text"); }, setClipboardText: function(event, value){ if (event.clipboardData){ event.clipboardData.setData("text/plain", value); } else if (window.clipboardData){ // 兼容IE window.clipboardData.setData("text", value); } } };var input = document.getElementById("name"); input.addEventListener("paste", function(event) { var data = event.clipboardData.getData("text"); console.log(data); if(!/^\d*$/.test(data)) { // 只允许粘贴数字 event.preventDefault(); } });1234567891011121314151617181920212223
3. 自动切换焦点
用户填写完当前字段时,自动将焦点切换到下一个字段。
<p>Enter your telephone number:</p><input type="text" name="tel1" id="txtTel1" size="3" maxlength="3" ><span>-</span><input type="text" name="tel2" id="txtTel2" size="3" maxlength="3" ><span>-</span><input type="text" name="tel3" id="txtTel3" size="4" maxlength="4" >123456
(function(){ function tabForward(event){ event = EventUtil.getEvent(event); var target = EventUtil.getTarget(event); if (target.value.length == target.maxLength){ var form = target.form; for (var i=0, len=form.elements.length; i < len; i++) { if (form.elements[i] == target) { if (form.elements[i+1]){ form.elements[i+1].focus(); } return; } } } } var textbox1 = document.getElementById("txtTel1"), textbox2 = document.getElementById("txtTel2"), textbox3 = document.getElementById("txtTel3"); EventUtil.addHandler(textbox1, "keyup", tabForward); EventUtil.addHandler(textbox2, "keyup", tabForward); EventUtil.addHandler(textbox3, "keyup", tabForward); })();12345678910111213141516171819202122232425
4. HTML5约束验证API
(1)必填字段:<input type="text" required />
(2)特殊输入类型:<input type="email | url" />
(3)数值范围:<input type="number" min="0" max="10" />
(4)输入模式:<input type="text" pattern="\d+" />
注意,模式的开头和末尾不用加^和$符合(默认已经有了)
(5)检测有效性:checkValidatity()
(6)禁用验证:
<!-- 整个表单不进行验证 --><form method="post" action="" novalidate ><!-- 某个按钮提交不必验证表单--><input type="submit" formnovalidate name="btnNoValidate" />1234
三、选择框脚本
<select>
和<option>
元素创建
HTMLSelectElement的属性和方法:
属性和方法 | 作用说明 |
---|---|
add(newOption, relOption) | 向控件中插入新项,其位置在相关项relOption之前 |
multiple | 是否支持多项选择 |
options | 所有项集合 |
remove(index) | 移除给定位置的选项 |
selectIndex | 基于0的选中项的索引,如果没有选中项,则该值为-1;对于支持多选的控件,只保存选中项的第一项索引 |
size | 选择框中可见的行数 |
HTMLOptionElement的属性和方法:
属性和方法 | 作用说明 |
---|---|
index | 当前选项在options集合中的索引 |
label | 当前选项的标签 |
selected | 当前选项是否被选中 |
text | 选项的文本 |
value | 选项的值 |
<form method="post" action="" id="myForm"> <label for="selLocation">Where do you want to live?</label> <select name="location" id="selLocation"> <option value="Sunnyvale, CA">Sunnyvale</option> <option value="Los Angeles, CA">Los Angeles</option> <option value="Mountain View, CA">Mountain View</option> <option value="">China</option> <option>Australia</option> </select> </form>12345678910
// 选择上述每个选项后,value值分别为:["Sunnyvale, CA", "Los Angeles, CA", "Mountain View, CA", "", "Australia"] document.getElementById("selLocation").value; // 获得第一个选项的文本和值 document.forms[0].elements["location"].options[0].text;document.forms[0].elements["location"].options[0].value;12345
(1)展示规则:有value属性且值不为空,则展示value属性的值;否则展示该项的文本值。
(2)value值规则:有value属性(不管是否为空),获得的都是对应value属性的值;否则为该项文本值。
1. 选择选项
function getSelectedOptions(selectbox){ var result = new Array(); var option = null; for (var i=0, len=selectbox.options.length; i < len; i++){ option = selectbox.options[i]; if (option.selected){ result.push(option); } } return result; }12345678910111213
2. 添加选项
(1)DOM方式
var newOption = document.createElement("option");newOption.appendChild(document.createTextNode("Option text"));newOption.setAttribute("value", "Option value");selectbox.appendChild(newOption);1234
(2)Option构造函数
var newOption = new Option("Option text", "Option value"); selectbox.appendChild(newOption);12
(3)选择框的add方法(最佳方案)
var newOption = new Option("Option text", "Option value"); selectbox.add(newOption, undefined); // 插入到最后12
3. 移除选项
(1)DOM方
selectbox.removeChild(selectbox.options[0]);1
(2)选择框的remov
selectbox.remove(0);1
(3)将相应的选项设置为null(遗留机制)
selectbox.options[0] = null;1
4. 移动和重排选项
DOM的appendChild方法(只能添加到最后),如果appendChild传入一个文档中已有的元素,那么就会先从该元素的父节点中移除它,再把它添加到指定的位置。
// 将第一个选择框中的第一个选项移动到第二个选择框中 var selectbox1 = document.getElementById("selLocations1"), selectbox2 = document.getElementById("selLocations2");selectbox2.appendChild(selectbox1.options[0]); 1234
DOM的insertBefore方法
// 将选择框中的选项向后移动一个位置 var optionToMove = selectbox.options[selectbox.options.length - 1]; selectbox.insertBefore(optionToMove, selectbox.options[0]);123
四、表单序列化
对表单字段的名称和值进行URL编码,使用“&”分隔;
不发送禁用的表单字段;
只发送勾选的复选框和单选按钮;
不发送type为“reset”和“button”的按钮;
选择框中每个选中的值单独条目发送;
五、富文本编辑
contenteditable:用户立即可编辑该元素
data:text/html, <html contenteditable>1
The above is the detailed content of Introduction to JavaScript form scripts. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Object-relational mapping (ORM) frameworks play a vital role in python development, they simplify data access and management by building a bridge between object and relational databases. In order to evaluate the performance of different ORM frameworks, this article will benchmark against the following popular frameworks: sqlAlchemyPeeweeDjangoORMPonyORMTortoiseORM Test Method The benchmarking uses a SQLite database containing 1 million records. The test performed the following operations on the database: Insert: Insert 10,000 new records into the table Read: Read all records in the table Update: Update a single field for all records in the table Delete: Delete all records in the table Each operation

Object-relational mapping (ORM) is a programming technology that allows developers to use object programming languages to manipulate databases without writing SQL queries directly. ORM tools in python (such as SQLAlchemy, Peewee, and DjangoORM) simplify database interaction for big data projects. Advantages Code Simplicity: ORM eliminates the need to write lengthy SQL queries, which improves code simplicity and readability. Data abstraction: ORM provides an abstraction layer that isolates application code from database implementation details, improving flexibility. Performance optimization: ORMs often use caching and batch operations to optimize database queries, thereby improving performance. Portability: ORM allows developers to

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Introduction to JS-Torch JS-Torch is a deep learning JavaScript library whose syntax is very similar to PyTorch. It contains a fully functional tensor object (can be used with tracked gradients), deep learning layers and functions, and an automatic differentiation engine. JS-Torch is suitable for deep learning research in JavaScript and provides many convenient tools and functions to accelerate deep learning development. Image PyTorch is an open source deep learning framework developed and maintained by Meta's research team. It provides a rich set of tools and libraries for building and training neural network models. PyTorch is designed to be simple, flexible and easy to use, and its dynamic computation graph features make

Object-relational mapping (ORM) is a technology that allows building a bridge between object-oriented programming languages and relational databases. Using pythonORM can significantly simplify data persistence operations, thereby improving application development efficiency and maintainability. Advantages Using PythonORM has the following advantages: Reduce boilerplate code: ORM automatically generates sql queries, thereby avoiding writing a lot of boilerplate code. Simplify database interaction: ORM provides a unified interface for interacting with the database, simplifying data operations. Improve security: ORM uses parameterized queries, which can prevent security vulnerabilities such as SQL injection. Promote data consistency: ORM ensures synchronization between objects and databases and maintains data consistency. Choose ORM to have

__proto__ and prototype are two attributes related to prototypes in JS. They have slightly different functions. This article will introduce and compare the differences between the two in detail, and provide corresponding code examples. First, let’s understand what they mean and what they are used for. proto__proto__ is a built-in property of an object that points to the prototype of the object. Every object has a __proto__ attribute, including custom objects, built-in objects, and function objects. By __proto__ genus

Knowledge review: Five key points in the JS caching mechanism, specific code examples are required. Introduction: In front-end development, caching is an important part of improving web page performance. The JavaScript caching mechanism refers to saving the acquired resources locally so that the cache can be directly used in subsequent accesses, thereby reducing resource loading time and network bandwidth consumption. This article will introduce the key points in the JS caching mechanism and provide specific code examples. 1. Cache type Strong cache Strong cache refers to setting the Exp in the HTTP response header
