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.
$('input[type=checkbox]').click(function(e) {
var num_checked = $("input[type=checkbox]:checked").length;
if (num_checked > 3) {
$(e.target).prop('checked', false);
}
});
You will need to store reference to the last selected checkbox. Maybe like this:
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.Check this out, the last will everytime change.
You can do it like fllowing.