Javascript 简明教程
JavaScript - DOM Forms
The DOM Forms
HTML DOM 文档 forms 用于从用户获取数据。
The HTML DOM document forms are used to get the data from the users.
在 JavaScript 中,可以使用 'document' 对象的 'forms' collection 来访问 HTML 文档的所有 <form> 元素。
In JavaScript, you can use the 'forms' collection of the 'document' object to access all <form> elements of the HTML document.
你可以访问特定表单的所有表单元素并对它们进行操作。使用 JavaScript,你可以验证表单值,处理表单数据提交等。
You can access all forms elements of particular forms and manipulate them. Using JavaScript, you can validate the form values, handle the form data submission, etc.
Syntax
遵循以下语法使用 'forms' 集合来操作 DOM 表单。
Follow the syntax below to use the 'forms' collection to manipulate the forms of the DOM.
document.forms;
此处,'forms' 是 'document' 对象的属性。
Here, 'forms' is a property of the 'document' object.
Properties of 'forms' Collection
Property |
Description |
length |
It represents the number of <form> elements in the HTML document. |
Methods of 'forms' Collection
Method |
Description |
[index] |
To get the particular <form> element from the 0-based index of the collection of HTML forms. |
item(index) |
To get the particular <form> element from the 0-based index of the collection of HTML forms. |
namedItem(id) |
To get the <form> element with a particular id. |
Return value
document.forms 以它们存在于 HTML 文档中的顺序返回所有表单的集合。
The document.forms returns the collection of all forms in the same order as they are present in the HTML document.
Example: Finding total <form> elements in the HTML document)
在下面的代码中,我们使用 'forms' 集合的 'length' 属性来查找 HTML 文档中存在的表单数量。
In the below code, we use the 'length' property of the 'forms' collection to find the number of existing forms in the HTML document.
<html>
<body>
<form>
<input type = "text" name = "first" id = "first" value = "First Name">
</form>
<form>
<input type = "text" name = "second" id = "second" value = "Last Name">
</form>
<form>
<input type = "text" name = "third" id = "third" value = "Contact">
</form>
<div id = "output">Total number of forms in the HTML document is: </div>
<script>
document.getElementById('output').innerHTML += document.forms.length;
</script>
</body>
</html>
Example: Get the id of all <form> elements
在下面的代码中,我们使用它的索引访问每个表单,并使用 'id' 属性来获取特定表单的 id。
In the below code, we access each form using its index and use the 'id' property to get the id of a particular form.
<html>
<body>
<form id = "form1">
<label for = "first"> Fruit Name: </label>
<input type = "text" name = "first" id = "first">
</form>
<form id = "form2">
<label for = "second"> Price: </label>
<input type = "text" name = "second" id = "second">
</form>
<form id = "form3">
<label for = "third"> Color: </label>
<input type = "text" name = "third" id = "third">
</form>
<div id = "output"> </div>
<script>
document.getElementById('output').innerHTML =
"Id of the first form is: " + document.forms[0].id + "<br>" +
"Id of the second form is: " + document.forms[1].id + "<br>" +
"Id of the third form is: " + document.forms[2].id;
</script>
</body>
</html>
Example: Get particular form using its id and namedItem() method
在下面的代码中,我们通过取 'forms' 集合作为引用,使用 namedItem() 方法来获取一个带有特定 id 的表单。
In the code below, we used the namedItem() method by taking the 'forms' collection as a reference to get a form with a particular id.
<html>
<body>
<form id = "form1">
<label for = "first"> First Name </label>
<input type = "text" name = "first" id = "first">
</form>
<form id = "form2">
<label for = "second"> Last Name </label>
<input type = "text" name = "second" id = "second">
</form>
<div id = "output">The innerHTML of the form element having id equal to form2 is: </div>
<script>
const output = document.getElementById('output');
output.innerHTML += document.forms.namedItem('form2').innerHTML;
</script>
</body>
</html>
JavaScript Form Submission
在 JavaScript 中,可以使用 'submit' 输入类型提交表单,并使用 onsubmit() 事件处理程序执行特定函数来处理表单数据。
In JavaScript, you can submit the form using the 'submit' input type and execute a particular function to handle the form data using the onsubmit() event handler.
Example
在下面的代码中,该表单获取用户的姓氏和名字。之后,当用户点击提交输入时,它将调用 submitForm() 函数。
In the below code, the form takes users' first and last names. After that, when users click the submit input, it calls the submitForm() function.
在 submitForm() 函数中,我们使用了 preventDefault() 方法来阻止在未提交表单的情况下执行该函数。
In the submitForm() function, we used the preventDefault() method to prevent the execution of the function without submitting the form.
随后,我们使用“forms”集合来访问表单及其输入字段的值。
After that, we use the 'forms' collection to access the form and values of its input fields.
最后,我们在输出中打印输入的值。
At last, we print the input values in the output.
<html>
<body>
<form onsubmit = "submitForm(event)" id = "nameform">
<p><label>First Name: </label><input type = "text" name = "firstname"></p>
<p><label>Last Name: </label><input type = "text" name = "lastname"></p>
<p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script>
function submitForm(e) {
e.preventDefault();
const output = document.getElementById('output');
const firstname = document.forms['nameform']['firstname'].value;
const lastname = document.forms['nameform']['lastname'].value;
output.innerHTML = "First Name: " + firstname + ", Last Name: " + lastname;
}
</script>
</body>
</html>
JavaScript Form Validation
在 JavaScript 中,您还可以验证表单以确保用户已填写必要的输入。您可以在表单提交时调用的函数中执行验证检查。
In JavaScript, you can also validate the form to ensure the users have filled the required inputs. You can perform the validation check in the function that you are invoking on form submit.
此外,当表单未满足特定条件时,您还可以在输出中显示错误信息。
Furthermore, you may also show the error message in the output if the form is not fulfilling the particular condition.
Example
在以下代码中,我们检查在用户提交表单时,名字和姓氏的长度是否小于 3。如果名字或姓氏的长度小于 3,我们显示错误信息。
In the below code, we check whether the length of the first name and last name is less than 3 when users submit the form. If the length of firstname or lastname is less than 3, we show the error message.
<html>
<body>
<form onsubmit = "submitForm(event)" id = "nameform">
<p>First Name: <input type = "text" name = "firstname"> </p>
<p>Last Name: <input type = "text" name = "lastname"> </p>
<p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script>
function submitForm(e) {
e.preventDefault();
const output = document.getElementById('output');
const firstname = document.forms['nameform']['firstname'].value;
const lastname = document.forms['nameform']['lastname'].value;
if (firstname.length < 3 || lastname.length < 3) {
output.innerHTML += "The length of the first name or last name should be greater than 3. <br>";
} else {
output.innerHTML = "First Name: " + firstname + ", Last Name: " + lastname;
}
}
</script>
</body>
</html>
JavaScript Form Data Validation
还需要验证输入数据。
It is also required to validate the input data.
出现这种情况时,您希望用户传递数字数据,但他们错误地传递了字符串数据。在这种情况下,开发人员需要验证数据并显示错误信息。
Sometimes, it happens that you want users to pass the numeric data, but they pass the string data by mistake. In such cases, developers are required to validate the data and show the error message.
您可以在客户端或服务器端验证数据。最佳实践是在客户端验证数据并将纯数据发送到服务器。
You may validate the data on the client side or server side. It is a best practice to validate the data on the client side and send pure data to the server.
Example
在以下代码中,我们创建了输入字段,以从用户获取电子邮件。当用户提交表单时,我们使用正则表达式和 test() 方法来检查他们是否在输入中传递了有效的电子邮件地址。
In the code below, we have created the input field to take emails from users. When users submit the form, we use the regex and test() method to check whether they have passed the valid email address in the input.
<html>
<body>
<form onsubmit = "submitForm(event)" id = "emailform">
<p>Email: <input type = "email" name = "email"> </p>
<p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script>
function submitForm(e) {
e.preventDefault();
const email = document.forms['emailform']['email'].value;
//Validate email using regex
const emailRegex = /^[a-z0-9]+@[a-z]+\.[a-z]{2,3}$/;
if (emailRegex.test(email)) {
document.getElementById('output').innerHTML = "Email is valid!";
} else {
document.getElementById('output').innerHTML = "Email is not valid!";
}
}
</script>
</body>
</html>
Form Validation Using the HTML Constraint
(Automatic form validation)
在 HTML5 中,引入了某些约束来验证表单。您可以将这些约束用作 HTML 元素的属性,如果输入不符合约束,它将阻止表单提交。
In HTML5, some constraints are introduced to validate the form. You can use these constraints as an attribute of the HTML element, and it prevents the form submission if the input doesn’t match the constraints.
下表包含约束及其说明。
The table below contains the constraints and their description.
Constraint |
Description |
disabled |
To disable the input element. |
max |
To specify the maximum value of the input element. |
min |
To specify the minimum value of the input element. |
pattern |
To specify the particular pattern for the input element. |
required |
To specify the input element as a required field. |
type |
To specify the type of the input element. |
Syntax
按照以下语法将上述约束作为属性添加到 <input> 元素。
Follow the syntax below to add the above constraints as an attribute to the <input> element.
<input attr=value >
Example: Using the required attribute
在下方的代码中,我们在 input 元素中使用了“required”属性。当你在没有在 input 字段中输入数字的情况下提交表单时,它将显示一条默认的错误消息。
In the below code, we used the 'required' attribute with the input element. When you submit the form without entering the number in the input field, it will show a default error message.
<html>
<body>
<form onsubmit = "submitForm(event)" id = "form">
<p>Number: <input type = "number" name = "num" required> </p>
<p><input type = "submit"></p>
</form>
<div id = "output"> </div>
<script>
function submitForm(e) {
e.preventDefault();
const num = document.forms['form']['num'].value;
document.getElementById('output').innerHTML += "The submitted numeric value is: " + num + "<br>";
}
</script>
</body>
</html>
HTML 表单验证约束提供了有限的功能。因此,你可以编写自定义的 JavaScript 函数来验证表单。
The HTML form validation constraints provide limited functionality. So, you can write a custom JavaScript function to validate the form.
你也可以使用 CSS 选择器来验证表单。
You may also use the CSS selectors to validate the form.