If checkbox :checked more than 3 last one should unchecked

穿精又带淫゛_ 提交于 2019-12-06 12:12:03

问题


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.

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

回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/35195235/if-checkbox-checked-more-than-3-last-one-should-unchecked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!