Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Show-Hide DIV based on Checkbox Value

Tags:

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();         }     });  } 
like image 639
mickormick Avatar asked Dec 14 '10 21:12

mickormick


People also ask

How do you show and hide div elements based on the click of checkboxes in jQuery?

In order to display data/content of a specific element by selecting the particular checkbox in jQuery we can use the toggle() method. The toggle() method is used to check the visibility of selected elements to toggle between hide() and show() for the selected elements.

How do you check checkbox is checked or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);


2 Answers

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();     } });  
like image 116
raymosley Avatar answered Oct 11 '22 12:10

raymosley


I use jQuery prop

$('#yourCheckbox').change(function(){   if($(this).prop("checked")) {     $('#showDiv').show();   } else {     $('#hideDiv').hide();   } }); 
like image 41
Cybercarnage シ Avatar answered Oct 11 '22 13:10

Cybercarnage シ