If checkbox :checked more than 3 最后一个应该取消选中

If checkbox :checked more than 3 last one should unchecked

我有 6 个input[type="checkbox"]

用户一次只能select 3 个复选框。
如果用户 select 是第 4 个复选框,那么上次选中的(第 3 个复选框)应该取消选中。

查找图片附件以便更好地理解。

同时,如果用户 select 倒数第 5 selected (4th) 应该 deselect。

因为,我无法创建此逻辑,所以我制作了 fiddle 演示,其中如果 selected 超过 3 个。当前的没有得到 select编辑

Find fiddle demo

$('input[type=checkbox]').click(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) { 
  $(e.target).prop('checked', false);
}
});

您需要存储对最后选中的复选框的引用。可能是这样的:

var lastChecked;

var $checks = $('input:checkbox').click(function(e) {
    var numChecked = $checks.filter(':checked').length;
    if (numChecked > 3) {
        alert("sorry, you have already selected 3 checkboxes!");
        lastChecked.checked = false;
    }
    lastChecked = this;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="" /> <br/>
<input type="checkbox" name="" /> <br/>
<input type="checkbox" name="" /> <br/>
<input type="checkbox" name="" /> <br/>
<input type="checkbox" name="" /> <br/>
<input type="checkbox" name="" />

我还通过在变量中缓存复选框集合来改进代码,这样您就不会一次又一次地重新查询 DOM。 :checkbox 选择器也很方便。

你可以像流水一样做。

var last;
$('input[type="checkbox"]').change(function () {
    if (this.checked) {
        if ($('input[type="checkbox"]:checked').length > 3) {
            $(last).prop('checked', false);
        }
        last = this;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />

var checked = [];
$('input[type=checkbox]').click(function(e) {
    var num_checked = $("input[type=checkbox]:checked").length;
    if (num_checked > 3) {
        checked[checked.length - 1].prop('checked', false);
        checked.pop();
    }
    if($.inArray($(this), checked) < 0){
        checked.push($(this));
    }
});

看看这个,最后一个每次都会变。