【问题标题】:Stop checking checkboxes after a number of checkboxes have been checked in jQuery or JavaScript在 jQuery 或 JavaScript 中选中多个复选框后停止选中复选框
【发布时间】:2015-12-05 18:17:28
【问题描述】:

在已经检查了一定数量的复选框后,我想阻止用户检查另一个复选框。即选中 3 个复选框后,用户无法再选中,并显示一条消息“您不能选择超过 3 个框。”

我快到了,但最后一个复选框仍在选中,我不希望这样,我希望在出现消息时取消选中它。

我该怎么做:

var productList = $('.prod-list'),
    checkBox = productList.find('input[type="checkbox"]'),
    compareList = $('.compare-list ul');

productList.delegate('input[type="checkbox"]', 'click', function () {
  var thisElem = $(this),
      thisData = thisElem.data('compare'),
      thisImg = thisElem.closest('li').find('img'),
      thisImgSrc = thisImg.attr('src'),
      thisImgAlt = thisImg.attr('alt');

  if (thisElem.is(':checked')) {
    if ($('input:checked').length < 4) {

        compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');

    } else {
        $('input:checked').eq(2).attr('checked', false);
        alert('You\'re not allowed to choose more than 3 boxes');
    }
  } else {
    var compareListItem = compareList.find('li');

    for (var i = 0, max = compareListItem.length; i < max; i++) {
        var thisCompItem = $(compareListItem[i]),
            comparingData = thisCompItem.data('comparing');

        if (thisData === comparingData) {
            thisCompItem.remove();
        }
    }

  }

});

【问题讨论】:

  • 你能分享你的 HTML 代码吗?
  • 哦,也许我误解了这个问题......你希望新的复选框被选中,但之前或第一个选中的复选框被取消?

标签: javascript jquery checkbox


【解决方案1】:

我可能误解了这个问题...请参阅我的评论。

为了防止选择,您可以调用event.preventDefault() 并使用event 参数定义处理程序。

$('input[type="checkbox"]').click(function(event) {
    if (this.checked && $('input:checked').length > 3) {
        event.preventDefault();
        alert('You\'re not allowed to choose more than 3 boxes');
    }
});

DEMO

或者,将this.checked 设置为false。这甚至会阻止浏览器呈现复选标记。

DEMO

【讨论】:

  • 谢谢菲利克斯,它有帮助
【解决方案2】:

一个 jquery 函数用于多个表单

<form>
 <input  type="checkbox" name="seg"><br>
 <input  type="checkbox" name="seg" ><br>
 <input  type="checkbox" name="seg"><br>
 <input  type="checkbox" name="seg"><br>
</form>

<br><br><br><br><br>

<form>
  <input  type="checkbox" name="seg1"><br>
 <input  type="checkbox" name="seg1" ><br>
 <input type="checkbox" name="seg1"><br>
 <input type="checkbox" name="seg1"><br>
</form>

$('input[type="checkbox"]').click(function(event) {
  if ($("input[name= "+ this.name +"]:checked").length > 3) {
        event.preventDefault();
        alert('You\'re not allowed to choose more than 3 boxes');
    }
});

【讨论】:

    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2012-07-18
    • 2012-02-02
    • 2015-02-18
    相关资源
    最近更新 更多