Reputation: 3228
I'm wondering how to see if all checkboxes are selected using jQuery.
Basically when all three options are selected I want to display only the mobile number.
If only the last option is selected show the home number.
If all three are selected show mobile and keep home hidden.
I've managed to get the case where if the user clicks on the last option show the home number but not if all three are selected.
See my jQuery below...
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();
});
Upvotes: 1
Views: 84
Reputation: 62488
you have to do this way:
$("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');
}
});
Upvotes: 1
Reputation: 221
you have 2 mistakes :
'this' is li,li's children is label ,not the input .so you need modify it to this:
$(this).find('input').prop( 'checked', !$(this).find('input').prop('checked') );
the input:checkbox element is not inside the form ,so you need to remove the form,like this:
if ($("input:checkbox:checked").length === 3)
good luck!
Upvotes: 1
Reputation: 7779
Guessing your html try something like this:
$('form input:checkbox').on('click', function(){
if ($('form input:checkbox').length == $('form input:checkbox:checked').length) {
console.log('All checkboxes are checked');
}
});
Edit:
Oh I see, the issue is your selector form input:checkbox:checked
since your checkboxes are not inside your form tag, you have two possible solutions: change <form>
to be the first line in your html or remove the word "form" from your selector
Also you have to do a handle for any checkbox not only the last one so you can verify the condition when any of them is clicked.
Upvotes: 1
Reputation: 2576
Try:
if($( "input:checked" ).length === 3) {
//show mobile number hide home
}
Upvotes: 1