If checkbox :checked more than 3 last one should u

2019-04-13 09:02发布

问题:

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.