使用jQuery检查页面加载时已检查输入的数量

Checking amount of checked inputs on page load using jQuery

本文关键字:检查 输入 加载 jQuery 使用      更新时间:2023-09-26

我有这个JS,当选择一定数量的项目将禁用其他选项,而选择这些项目将更新计数,但效果很好!当我将这些添加到购物车中时,我可以在购物车中进行编辑,因此当我单击编辑时,它会返回到产品页面,我选择了客户在添加到购物车时选择的选项,但我的计数显示0(3),其他选项未禁用。

我知道我需要做一个每/foreach页面加载检查是否有复选框被选中,如果是这样,并在限制禁用其他等,但它花了我一段时间。我需要一些帮助来把它放到小提琴的位置。我如何检查这些货物的装载情况?

原始小提琴: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);
  });
});

认为您说您希望.change()处理程序不仅在单击复选框时运行,而且在页面加载时也运行。

如果是这样,只需在将.change()处理程序绑定到现有的ready处理程序中后,自己手动触发一次:

$(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
});

演示:https://jsfiddle.net/ate9a04u/6/