Default restriction Checked by checkboxes

I have a problem regarding how I will limit my checkbox to the default. for example, I have 7 flags. and I want to limit it to the three flags checked by default after the page loads.

this should be the output: Checkbox1 : true Checkbox2 : true Checkbox3 : true Checkbox4 : false Checkbox5 : false Checkbox6 : false Checkbox7 : false 

Here is my sample code:

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

I mean this, I don’t know where I will put my counter (mvp) inside each of my functions. In this code all my flags are checked: D.

Sorry for the newbies question, please help me ..

+2
source share
7 answers

In fact, there is no need for a counter, since each function will pass in the index. Just use the index as a counter.

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

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

+2
source

Using the jquery :lt selector, it will match all elements with a lower index.

Example:

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

Based on @Kevin Bowersox code:

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

i changed this code as follows:

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

Do not set the default state of your page using Javascript, use the "checked" HTML 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 flag will be checked.

0
source

demo

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

Decrement mvp after checking each flag. When it reaches 0, start unchecking.

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

Check it out . slice

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

See JS script

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

0
source

All Articles