cazlouise cazlouise - 1 month ago 8
jQuery Question

Hide a button unless checkbox is selected

I want to hide the submit in a form button unless at least one of the checkboxes is selected. Here is a sample of my view



$(document).ready(function() {
$('input[type=checkbox]').click(function() {
if ($("#radiobutton :checked") {
$('#next-container').toggle();
} else {
$('#next-container').hide()
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="radio" id="radio">

<div id="nxtbutton">
<div id="next-container">
<button class="card__btn btn" id="nxtBtn" type="button">Next</button>
</div>
</div>




Answer

Change the length of the checked boxes inside a change event handler, if any are checked, show the button

$(document).ready(function() {
   var boxes = $(' input[type=checkbox]').on('change', function() {
    var flag = boxes.filter(':checked').length > 0;

    $('#next-container').toggle(flag);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="radio" id="radio">
<input type="checkbox" checked name="radio" id="radio">
<input type="checkbox" checked name="radio" id="radio">
<input type="checkbox" checked name="radio" id="radio">
<br />
<div id="nxtbutton">
  <div id="next-container">
    <button class="card__btn btn" id="nxtBtn" type="button">Next</button>
  </div>
</div>