Hardist
Hardist

Reputation: 1993

jQuery show/hide div onclick checkbox multiple

My fiddle works, but what I need is for the hidden div to STAY displayed if I click multiple checkboxes. And I need it only to HIDE once NO checkbox is clicked anymore. So for example, I click the first checkbox, the div shows. I click the second, the div stays. I uncheck the second, the div stays. I uncheck the first (which means none are checked again) and the div hides. I tried using slideToggle but it doesn't hide once no checkboxes are checked anymore.

https://jsfiddle.net/6zsdLa5p/

HTML:

<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" /><br />
<input type="checkbox" value="ui-options" />

<br /><br />

<div class="ui-options">
show me!
</div>

CSS:

.ui-options {
display:none
}

JS:

$('input[type="checkbox"]').click(function(){
    if($(this).attr("value")=="ui-options"){
        $(".ui-options").slideToggle(150);
    }
});

Upvotes: 0

Views: 3450

Answers (2)

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

// find the <input> elements whose type is equal to 'checkbox',
// bind a change event-handler to those elements:
$('input[type="checkbox"]').change(function() {

  // selecting the <div> element(s) with a class of
  // 'ui-options', then using a ternary within the square brackets,
  // if there are checked <input> elements, we use the slideDown
  // method (to show) if there are no checked <input> elements
  // we use the slideUp method (to hide):
  $('div.ui-options')[$('input[type=checkbox]:checked').length ? 'slideDown' : 'slideUp']('fast');
});

$('input[type="checkbox"]').change(function() {
  $('div.ui-options')[$('input[type=checkbox]:checked').length ? 'slideDown' : 'slideUp']('fast');
});
.ui-options {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<input type="checkbox" value="ui-options" />
<br />
<br />
<div class="ui-options">show me!</div>

External JS Fiddle demo for experimentation.

References:

Upvotes: 3

D.K.
D.K.

Reputation: 478

Using toggle, you are hiding/showing the div each time you click the checkbox. You need to check if there are any "checked" checkboxes and decide if you want to show or hide your div. For example like this:

$('input[type="checkbox"]').click(function(){
    if($('input[type="checkbox"]:checked').length > 0)
        $(".ui-options").slideDown(150);
    else
        $(".ui-options").slideUp(150);
});

Upvotes: 2

Related Questions