Set the total number of checkboxes in an array
I have a checkbox like this
for($j=1;$j<=10;$j++)
<input type="checkbox" name="chkLimit[]" id="chkLimit_<?php echo $j;?>" value="<?php echo $j;?>" />
i got 10 checkbox
and i will write jquery code like this ...
$(document).ready(
function (){
setLimitSelection();
}
);
function setLimitSelection(){
$('input[name="chkLimit[]"]').limitSelection(
{
// number of items to limit to
limit: 4,
// on error, do this
onfailure: function (n){
$("#idCheckboxMsg").html(
"You can not select more than " + n + " items."
);
return false;
},
// on success, do this
onsuccess: function (n){
$("#idCheckboxMsg").html("");
return false;
}
}
);
$('select[name="selLimit[]"]').limitSelection(10);
}
$("input.chkLimit").click(function() {
var numSelected = $("input.chkLimit[]:checked").length;
var numLeft = 10 - parseInt(numSelected);
$("#statusBox").html("You have "+numSelected+" CD selected.<br>You have "+numLeft+" selections left.");
});
what i want: user cannot select more than 4 checkboxes
thank
+1
source to share
2 answers
I haven't tested this, but it should do the job for you:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(
var checked = $("#myCheckboxes input[type='checkbox'][checked]").length;
if(checked == 4){
$("#myCheckboxes input[@type='checkbox']").not(":checked").attr('disabled',true);
}else{
$("#myCheckboxes input[@type='checkbox']").not(":checked").attr('disabled',false);
}
)
});
Every time the checked state of a checkbox changes, it checks how many checkboxes are checked. If there are 4, it disables unchecked fields, otherwise it allows them. This assumes they all live in a container called#myCheckboxes
0
source to share
It looks like @inkedmn had some syntax errors, but the comment field is just not enough for development. So here's what I think he is trying to do:
$(function(){
$("#myCheckboxes input[type='checkbox']").change(function() {
var checked = $("#myCheckboxes input[type='checkbox']:checked").length;
if(checked == 4){
$("#myCheckboxes input[type='checkbox']")
.attr('disabled',true)
.filter(':not(:checked)')
.attr('disabled',false);
} else {
$("#myCheckboxes input[type='checkbox']").attr('disabled',false);
}
)
});
This should do it for you.
0
source to share