JavaScript 中的单选按钮验证
本文将讨论 JavaScript 中的单选按钮验证。
JavaScript 中的单选按钮验证
<input>
单选项目通常用于单选组,单选按钮的集合,描述一组相关选项。一次只能选择给定组中的一个选项。
如果要选择多个选项,请使用 Checkbox
而不是 RadioButton
。单选按钮通常表示为选中时填充或突出显示的小圆圈。
语法:
<input type="radio">
通过为组中的每个选项按钮赋予相同的名称来定义选项组。设置选项组后,选择选项按钮会取消选择同一组中所有当前选择的选项按钮。
你可以在一个页面上拥有任意数量的选项组,只要每个组都有其唯一的名称。提交表单时,你应该始终指定 value 属性以将信息传递到服务器。
如果未指定 value 属性,表单数据将为整个单选组分配值 on
。
让我们举一个例子,我们询问用户的性别。
创建三个单选按钮,将 name
属性设置为 gender
,并具有 Male
、Female
和 Other
值。该表格应使用性别进行验证,如果没有性别,则应发出警报。
<form onsubmit="return (checkForm())" name="userForm">
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="Other">
<label for="other">Other</label>
<br>
<input type="submit" value="Submit">
</form>
function checkForm() {
let chosenOption = '';
const len = document.userForm.gender.length;
for (i = 0; i < len; i++) {
if (document.userForm.gender[i].checked) {
chosenOption = document.userForm.gender[i].value
}
}
if (chosenOption == '') {
alert('Please choose your gender!');
return false;
} else {
console.log(chosenOption)
}
}
在示例中,我们首先检查了选项的长度。之后,我们遍历选项并检查是否检查了任何选项。
如果不是,我们返回 false
并向用户显示警报以填写选项。
当你在任何浏览器中运行代码时,它将呈现表单。选择性别并按提交;它将打印性别。
如果没有选择性别,它会提示选择性别。
输出:(选择选项时)
"Female"
输出:(当没有选择选项时)
你可以在此处运行本教程中讨论的代码。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。