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();
}
});
}
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();
}
});
I use jQuery prop
$('#yourCheckbox').change(function(){
if($(this).prop("checked")) {
$('#showDiv').show();
} else {
$('#hideDiv').hide();
}
});
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();
}
});
}
to check if any of the checkboxes is checked (lots of checks in this line..).
reference: http://api.jquery.com/checked-selector/
ebdiv is set style="display:none;"
it is works show & hide
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
You might consider using the :checked
selector, provided by jQuery. Something like this:
$('.pChk').click(function() {
if( $('.pChk:checked').length > 0 ) {
$("#ProjectListButton").show();
} else {
$("#ProjectListButton").hide();
}
});
A tip to all people that use flat-red, flat-green plugin, because of this plugin the answers above wont work!
In that case, use onchange="do_your_stuff();" on the label, for example: Your checkbox here
The reason why it doesn't work is that this Jquery creates a lot of objects around the real checkbox, so you can't see if it's changed or not.
But if someone click straight on checkbox, won't work :'(
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
来源:https://stackoverflow.com/questions/4444292/jquery-show-hide-div-based-on-checkbox-value