Limiting Default Checked checkboxes

心已入冬 提交于 2019-12-06 12:35:18

There is actual no need for a counter since the each function will pass in the index. Just use the index as the counter.

$(document).ready(function() {
    $("input:checkbox").each(function( index ) {
           this.checked = (index < 3);
    });
});

JS Fiddle: http://jsfiddle.net/SB6aD/2/

Using jquery :lt selector,it will match all element which has a smaller index.

Example:

$(function() {
  var mvp = 3;
  $('input:checkbox:lt('+mvp+')').prop('checked', true);
});

Based of @Kevin Bowersox's code:

var mvp = 3;
$(document).ready(function() {
    var counter = 0;
    $("input:checkbox").each(function( index ) {
        if(counter < mvp){
           $(this).attr("checked",true);
           counter++;
        }
    });
});

i modified this code into this:

var mvp = 3;
    $(document).ready(function() {
$("input:checkbox").each(function( index ) {
        if(index < mvp){
           $(this).attr("checked",true);
        }
    });
});

Don't setup the default state of your page with Javascript, use the HTML "checked" attribute.

<form action="demo_form.asp">
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
  <input type="submit" value="Submit">
</form>

In this example the car checkbox will be checked.

Decrement mvp after you check each checkbox. When it reaches 0, start unchecking.

$(document).ready(function() {
    var mvp = 3;
    $("input:checkbox").each(function( index ) {
        ($this).attr("checked", mvp > 0);
        mvp--;
    });
});

Check .slice

$(function() {
  var mvp = 3;
  $('input:checkbox').slice(0, mvp).prop('checked', true);
  $('input:checkbox').slice(mvp).prop('checked', false);
});

See the JS Fiddle

And note, checked is rather a property than an attribute, use .prop instead of .attr.

demo

$(document).ready(function() {
    var checkboxes = $("input:checkbox");
    checkboxes.each(function( index ) {
        if (checkboxes.filter(':checked').length >= 3) {return;}
        this.checked = true;

    });

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