Reputation: 327
Hello i want to display a div when a checkbox is checked. The thing is i have multiple selects and i want to display the form until none is selected. My code is not working exactly as it should because when i deselect a checkbox my div dissapears and it should dissapear only if none is selected.
Here is my js
$('.checkbox').click(function() {
if( $(this).is(':checked')) {
$("#formular").show();
} else {
$("#formular").hide();
}
});
also jsfiddle http://jsfiddle.net/bYuak/
Upvotes: 1
Views: 100
Reputation: 1427
try this
$('.checkbox').click(function() {
if($(".checkbox:checked").length){
$("#formular").show();
}
else{
$("#formular").hide();
}
});
or
$('.checkbox').click(function() {
$("#formular").toggle($(".checkbox:checked").length>0);
});
Upvotes: 1
Reputation: 3827
This is how I do it:
function checkCount() {
// Store count of how many selected
var boxCount = 0,
el = $("#formular");
// Go through each checkbox
$(".checkbox").each(function (index) {
//Increase count if checked
if ($(this).is(':checked')) {
boxCount++;
}
});
if (boxCount > 0) {
el.show();
}
else {
el.hide();
}
}
$('.checkbox').on('change', function () {
checkCount();
});
Upvotes: 1
Reputation: 28126
Its simple just target all checkboxes when you check.
$('.checkbox').click(function() {
if( $('.checkbox').is(':checked')) {
$("#formular").show();
} else {
$("#formular").hide();
}
});
See Fiddle: http://jsfiddle.net/bYuak/2/
Upvotes: 1
Reputation: 6909
Your code is called any time a click event is generated for any of your checkboxes, this happens because of this line of code:
$('.checkbox').click()
In side the event handler, you say :
if( $(this).is(':checked')) {
$("#formular").show();
}
Which shows the div, and the else statement hides the div, if that element is unchecked. Therefore your code is working as expected. Your implementation however is very different to what you want it to do.
You need to check the state of all the checkboxes, using a loop and then show/hide the #formular div, if they are ALL unchecked.
Upvotes: 1
Reputation: 388446
Try
var $checks = $('.checkbox').click(function () {
$("#formular").toggle($checks.filter(':checked').length>0);
});
Demo: Fiddle
Upvotes: 3