James James - 3 months ago 8
HTML Question

jQuery: Checking amount of checked inputs on page load

I have this JS that when selecting a certain amount of items will disable the other options and while selecting those items will update the count which works great however! im at the point when i add these to a cart, and in the cart i can edit so when i click edit it comes back to the product page and i have the options selected that were selected by the customer when adding to the cart but.... my count shows 0 of 3 and the other options are not disabled.

I know i would need to do a each / foreach on page load to check if any checkboxes are checked and if so and at limit diable others etc... but took me a while and some help here to get it to where it is in this fiddle... im new to JS / jQuery so wondering if someone could help me out maybe and check for these on load?

Original Fiddle:

https://jsfiddle.net/ate9a04u/2/

JS:

$(document).ready(function() {
var maxAllowed = 3;
$(".rmax").html(maxAllowed);

$(".subscribtion-content input.checkbox").change(function() {
var checkBox = $(".subscribtion-content input.checkbox")
var cnt = $(".subscribtion-content input.checkbox:checked").length;
if (cnt == maxAllowed) {
checkBox.not(':checked').prop('disabled', true);
} else {
checkBox.not(':checked').prop('disabled', false);
}

$(".rcount").html(cnt);
});
});

Answer

I think you're saying you want the same processing that the .change() handler does to run not just when a checkbox is clicked but also on page load.

If so, just manually trigger the .change() handler yourself once right after binding it in your existing ready handler:

$(document).ready(function() {
  var maxAllowed = 3;
  $(".rmax").html(maxAllowed);

  $(".subscribtion-content input.checkbox").change(function() {
    var checkBox = $(".subscribtion-content input.checkbox")
    var cnt = $(".subscribtion-content input.checkbox:checked").length;
    if (cnt == maxAllowed) {
      checkBox.not(':checked').prop('disabled', true);
    } else {
      checkBox.not(':checked').prop('disabled', false);
    }

    $(".rcount").html(cnt);
  }).change();  // <--- this is all you need to add
});

Demo: https://jsfiddle.net/ate9a04u/6/