我想知道如何使用jQuery选择所有复选框。
基本上,当选择所有三个选项时,我想只显示手机号码。
如果仅选择最后一个选项,则显示家庭电话号码。
如果所有三个都被选中显示移动并保持隐藏。
我设法得到的情况是,如果用户点击最后一个选项显示家庭号码,但如果所有三个都被选中,则不会。
请参阅下面的jQuery ...
var form = {
init: function() {
form.selection();
form.showHomeNumber();
},
selection: function() {
var option = $('.checkbox');
option.on('click', function(e){
e.preventDefault();
$(this).toggleClass('active');
$(this).children().prop( 'checked', !$(this).children().prop('checked') );
});
},
//If I select only the last option show home number
showHomeNumber: function() {
var homeNumber = $('.home-number'),
lastOption = $('.last-option'),
mobileNumber = $('.mobile-number');
lastOption.on('click', function(e){
e.preventDefault();
//If all three are selected show mobile, hide home
if ($("form input:checkbox:checked").length === 3) {
mobileNumber.css('display', 'block');
homeNumber.hide();
}
//If select last option only show home
homeNumber.toggleClass('home-active');
//If select last option only hide mobile
mobileNumber.toggleClass('mobile-inactive');
});
}
}
$(function(){
form.init();
});
答案 0 :(得分:1)
猜猜你的html尝试这样的事情:
$('form input:checkbox').on('click', function(){
if ($('form input:checkbox').length == $('form input:checkbox:checked').length) {
console.log('All checkboxes are checked');
}
});
修改强>
哦,我知道,问题是您的选择器form input:checkbox:checked
,因为您的复选框不在您的表单标记内,您有两种可能的解决方案:将<form>
更改为HTML中的第一行或删除word&#34; form&#34;来自您的选择器
此外,您必须为任何复选框执行句柄,而不仅仅是最后一个复选框,以便您可以在单击任何复选框时验证条件。
答案 1 :(得分:1)
尝试:
if($( "input:checked" ).length === 3) {
//show mobile number hide home
}
答案 2 :(得分:1)
'这'是li,li的孩子是标签,而不是输入。所以你需要修改它:
$(this).find('input').prop( 'checked', !$(this).find('input').prop('checked') );
input:复选框元素不在表单内,因此您需要删除表单,如下所示:
if ($("input:checkbox:checked").length === 3)
祝你好运!
答案 3 :(得分:1)
你必须这样做:
$("li.checkbox").on('click', function (e) {
e.preventDefault();
//If all three are selected show mobile, hide home
if ($("ul li.checkbox.active").length > 1) {
mobileNumber.css('display', 'block');
homeNumber.hide();
} else if ($("li.last-option").hasClass("active")) {
//If select last option only show home
homeNumber.toggleClass('home-active');
homeNumber.show();
mobileNumber.hide();
//If select last option only hide mobile
mobileNumber.toggleClass('mobile-inactive');
}
});