jQuery Show-Hide DIV based on Checkbox Value
Using AJAX I populate a DIV with a bunch of checkboxes (each with it's own unique ID). The IDs are "projectID1", "projectID2", "projectID3" and so on... I have given all checkboxes a class of "pChk".
My end goal is to show the DIV containing the Submit Button if ANY of the checkboxes are checked. The only time the DIV containing the Submit Button show be hidden is if all checkboxes are unchecked.
However the code I have come up with below shows/hides the Submit Button DIV for each checkbox instance. In other words, if I have three checkboxes CHECKED and I UNCHECK one of them, the Submit Button DIV get hidden.
Your expert advice is more than welcome!
function checkUncheck() {
$('.pChk').click(function() {
if (this.checked) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
}
Answer:
While this is old if someone comes across this again (via search). The correct answer with jQuery 1.7 onwards is now:
$('.pChk').click(function() {
if( $(this).is(':checked')) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
or
That is because you are only checking the current checkbox.
Change it to
function checkUncheck() {
$('.pChk').click(function() {
if ( $('.pChk:checked').length > 0) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
}