jQuery show/hide div onclick checkbox multiple

Hardist

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);
    }
});
David says reinstate Monica

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:

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related