javascript - 检查jquery中的复选框
问题描述
我是初学者网络开发人员;我在 Html/Css/jQuery 中制作我的项目。
我在网站上有 5 个复选框。其中 3 个具有 checkboxRequired 类。单击 5 个复选框中的每一个后,我必须检查是否所有 3 个带有 checkboxRequired checkout 的复选框都被选中。
我尝试这个解决方案:
$('input[type="checkbox"]').click(function(){
if($('input:checkbox.checkboxRequired').prop('checked')){
console.log("Checkbox is checked.");
}
else {
console.log("Checkbox is unchecked.");
}
});
但它总是显示:复选框未选中。
我该如何修复它?
请帮我。
解决方案
您需要使用 .is() 方法和 :checked 选择器。
单击复选框时 - 您使用所需的类(使用 .each() 方法)迭代复选框,并可以测试每个复选框以查看其是否选中。
请注意其中的小三元方程来演示传统 if/else 块的替代方案 - 但它做同样的事情(“?”行相当于 true,“:”相当于 false / else ....
编辑 - 我已经更新了功能以满足您的需求。基本上你需要检查是否所有的复选框都被选中,如果是 - 提交表单,如果没有 - 引发错误模式。
以下修改后的代码应该为您做到这一点。
$('input[type="checkbox"]').click(function(){
let total = 0;
let checked = 0;
$('.checkboxRequired').each(function(index){
total += 1;
if( $(this).is(':checked') ) {checked +=1 }
})
total === checked
? ($('.orderForm').submit(), console.log('Form Submitted'))
: $('#errorModal').modal('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 1</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 2</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 3</label><br/>
<label> <input type="checkbox" class="checkbox checkboxRequired"/> Checkbox 4</label><br/>
<label> <input type="checkbox" class="checkbox "/> Checkbox 5</label>
<!-- form
<form class="orderForm" method="post"></form>
-->
<!-- Modal -->
<div id="errorModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Error Modal Header</h4>
</div>
<div class="modal-body">
<p>There is a disturbance in the force..... not all required checkboxes are checked</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
推荐阅读
- c - 更改密码不会保留在 linux 影子文件中
- python - if 语句 python 用于列值
- c# - Asp.net 验证器失败计数器
- css - 如何在智能手机的woo commerce(wordpress)的商店页面上增加两个产品之间的空间
- android-sqlite - sqlite 数据库 /retrofit (json 对象)
- mysql - 为什么我不能用 Max date 加入这个查询?
- c# - 在 C# Web 应用程序中从命令提示符执行命令
- java - 无法在回收视图中获取文本
- xcode - 你如何通过 Mac 上的终端下载 SQLite for Xcode
- django - 当用户已经登录时,如何禁止用户进入注册页面?Django 2.1.2