If checkbox :checked more than 3 last one should u

2019-04-13 08:38发布

I have 6 input[type="checkbox"].

User can select only 3 checkbox at a time.
If user selects the 4th checkbox then last checked(3rd checkbox) should unchecked.

Find image attachment for better understanding.

enter image description here

Meanwhile, if User selects 5th last selected (4th) should deselect.

As, I'm not able to create this logic so that I made fiddle demo in which if selected more than 3. The current one is not getting selected.

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

3条回答
神经病院院长
2楼-- · 2019-04-13 09:25

You will need to store reference to the last selected checkbox. Maybe like this:

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="" />

I also improved code a little by caching checkbox collection in variable so you don't re-query DOM again and again. :checkbox selector is handy too.

查看更多
等我变得足够好
3楼-- · 2019-04-13 09:30
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));
    }
});

Check this out, the last will everytime change.

查看更多
欢心
4楼-- · 2019-04-13 09:33

You can do it like fllowing.

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" />

查看更多
登录 后发表回答