Codded
Codded

Reputation: 1256

Jquery if all checkboxes selected show() ... else hide()

I have 3 checkboxes and 2 divs. I want to be able to show one div when all 3 checkboxes have been ticked and show the other div when any other combination of checkboxes are ticked (ie not all 3). It would be very much appreciated if anybody could help me out with some suggestions. Thanks in advance.

<input id="1" type="checkbox" />
<input id="2" type="checkbox" />
<input id="3" type="checkbox" />

<div id="checked1">Title</div>

<div id="checked2" style="display:none;"><span style="color:green;">Title</span></div>


$(document).ready(function() {

$(('input#1')&&('input#2')&&('input#3')).change(
    function() {
        if ($(this).is(':checked')) {
             $("#checked2").show();
             $("#checked1").hide();

        } else {
              $("#checked1").show();
             $("#checked2").hide();
            }
    });
});

Upvotes: 1

Views: 1256

Answers (3)

Alnitak
Alnitak

Reputation: 339836

$(':input[type="checkbox"]').change(function() {

    var checked = true; // assume checked

    $(':input[type="checkbox"]').each(function() {
        if (!this.checked) {
            checked = false; // set false if any are unchecked, exit loop
            return false;
        }
    });

    if (checked) {
        $('#checked2').show();
        $('#checked1').hide();
    } else {
        $('#checked1').show();
        $('#checked2').hide();
    }
});

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

You cannot have ids starting or just the number. Try this

<input id="chk1" type="checkbox" />
    <input id="chk2" type="checkbox" />
    <input id="chk3" type="checkbox" />





var chkBoxes = $('#chk1,#chk2,#chk3');

      chkBoxes .change(function(){

      if (chkBoxes.filter(':checked').length == chkBoxes.length){
        $('#checked2').show();
        $('#checked1').hide();
      }else{
        $('#checked2').hide();
        $('#checked1').show();
      }
    });

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101614

var $cBoxes = $('#1,#2,#3');

$cBoxes.change(function(){
  // check if all are checked based on if the number of checkboxes total
  // is equal to the number of checkboxes checked
  if ($cBoxes.length == $cBoxes.filter(':checked').length){
    $('#checked2').show();
    $('#checked1').hide();
  }else{
    $('#checked2').hide();
    $('#checked1').show();
  }
});

Something like that?

Upvotes: 2

Related Questions