Skip to content Skip to sidebar Skip to footer

Must Have All 3 Checked Boxes Checked To Enable Button

I need some assistance with the following script. I'm using this as a pop up when someone is trying to add a product to the cart. Currently the button will become active if one of

Solution 1:

First of all id is unique you can't use the same id for more than one element instead use class

var numItems = $('.checkbox').length; //number of checkboxes
var checked = 0;

$('.checkbox').each(function() {
if ( $(this).prop('checked') ) { 
checked++;
}
});

if (numItems === checked) 
$("#mainbutton").removeAttr('disabled');
 else
alert('please check all the checkboxes');

don't forget to change all the id="checkbox" to class="checkbox"


Solution 2:

Update Fixed where I had the logic inverted.

As alread mentioned Id must be unique.

This can be done withouth the each loop however. Use :not in conjunction with :checked to see if there are any unchecked boxes.

$(document).ready(function() {
  $(".vet-diet-info [name='checkbox']").click(function() {;
    $("#mainbutton").prop("disabled", $(".vet-diet-info [name='checkbox']:not(:checked)").length !== 0);
    console.log($("#mainbutton").prop("disabled"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="vet-diet-info">

    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <label>
        <input name="checkbox" type="checkbox">Agree.
      </label>
    </p>
    <p>
      <a id="mainbutton" href="javascript:void(0)" data-dismiss="modal" class="btn btn-info" disabled="disabled">Confirm Purchase</a>
    </p>
  </div>
</div>

Post a Comment for "Must Have All 3 Checked Boxes Checked To Enable Button"