
本文介绍了如何使用 jQuery 动态获取页面上所有未选中复选框对应的标签文本,并将其存储到一个数组中。通过该方法,你可以方便地在表单提交或其他交互场景中获取这些标签值,并进行后续处理,例如发送到服务器端。
以下是如何使用 jQuery 获取未选中复选框标签值的详细步骤:
引入 jQuery 库: 确保你的 HTML 文件中已经包含了 jQuery 库。你可以从 jQuery 官网下载,或者使用 CDN 引入。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
编写 jQuery 代码: 使用 jQuery 选择器找到所有未选中的复选框,然后遍历它们,获取它们对应的标签文本,并将其存储到一个数组中。
$(document).ready(function() {
var unCheckedLabelText = []; // 用于存储未选中复选框的标签文本
$('.checkboxClass').click(function() {
unCheckedLabelText = []; // 每次点击时清空数组
$("input:checkbox:not(:checked)").each(function() {
var text = $(this).next('label').text(); // 获取标签文本
unCheckedLabelText.push(text); // 将标签文本添加到数组中
});
console.log(unCheckedLabelText); // 输出数组,用于调试
// 在这里可以将 unCheckedLabelText 发送到服务器端,或者进行其他处理
});
});代码解释:
HTML 结构: 确保你的 HTML 结构如下所示,复选框和标签是相邻的,并且标签紧跟在复选框后面。
<input type="checkbox" id="firstCheckbox" name="firstCheckbox" class="checkboxClass"> <label for="firstCheckbox">Attendance to shifts are regular and no last minute shift cancellation</label> <input type="checkbox" id="secondCheckbox" name="secondCheckbox" class="checkboxClass"> <label for="secondCheckbox">Attendance to shifts are regular and no last minute shift cancellation</label>
注意: for 属性的值必须与复选框的 id 属性的值相同,这样点击标签时才能选中或取消选中复选框。
<!DOCTYPE html>
<html>
<head>
<title>获取未选中复选框的标签值</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var unCheckedLabelText = [];
$('.checkboxClass').click(function() {
unCheckedLabelText = [];
$("input:checkbox:not(:checked)").each(function() {
var text = $(this).next('label').text();
unCheckedLabelText.push(text);
});
console.log(unCheckedLabelText);
});
});
</script>
</head>
<body>
<input type="checkbox" id="firstCheckbox" name="firstCheckbox" class="checkboxClass">
<label for="firstCheckbox">Attendance to shifts are regular and no last minute shift cancellation</label><br>
<input type="checkbox" id="secondCheckbox" name="secondCheckbox" class="checkboxClass">
<label for="secondCheckbox">Attendance to shifts are regular and no last minute shift cancellation</label><br>
<input type="checkbox" id="thirdCheckbox" name="thirdCheckbox" class="checkboxClass">
<label for="thirdCheckbox">Another checkbox example</label><br>
</body>
</html>本文介绍了如何使用 jQuery 获取未选中复选框的标签值。通过这种方法,你可以方便地在表单提交或其他交互场景中获取这些标签值,并进行后续处理。 记住根据你的实际 HTML 结构和需求,修改代码中的选择器和事件绑定。
以上就是如何使用 jQuery 获取未选中复选框的标签值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号