Reputation: 6799
I have the following checkbox
<input type="checkbox" name="compare[]" value="<?php echo $product_id ?>" />
Now, I want to let my users select minimum three and maximum three options from the above check box. Breaking of any of the rules would give a message.
Would you please kindly help me how to do that with Jquery?
Thanks in Advance
Upvotes: 0
Views: 480
Reputation: 36
You can loop over your checkbox's using jQuery.each(), checking for checked items and adding checks to a count. Then if the count is not equal to 3 you can output the validation error message.
$(function(){
$("#frm").submit(function(){
var checkCount = 0;
var min = 3;
var max = 3;
// iterate over checkbox's using jquery each()
// use jquery's attribute contains selector ( http://api.jquery.com/attribute-contains-selector/ )
// to grab the compare portion of the checkbox field name
$("input[name*='compare']").each(function(k, v) {
// increment check count when a checked checkbox is found
if($(this).is(":checked"))
checkCount++;
});
//validate checkbox count against predefined range
if(checkCount < min || checkCount > max)
{
console.log("Checkbox Validation Failed");
return false;
}
else
console.log("Checkbox Validation Passed");
});
});
Upvotes: 0
Reputation: 11445
Here is a 1 solution
var $chkbox = $('input[name=compare]');
$chkbox.click(function (e) {
if ($chkbox.filter(':checked').length > 3) {
e.target.checked = false;
}
});
var $chkbox = $('input[type="checkbox"]');
$chkbox.click(function (e) {
if ($chkbox.filter(':checked').length > 3) {
e.target.checked = false;
}
});
Upvotes: 2
Reputation: 9709
Try this plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Upvotes: 0