jQuery Show-Hide DIV based on Checkbox Value

mickormick picture mickormick · Dec 14, 2010 · Viewed 102.5k times · Source

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

raymosley picture raymosley · Apr 16, 2012

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();
    }
});