I am using jQuery Validation plugin to validate check box since it does not have default option, One should be selected and max two check boxes can be selected, these is the criteria. I am not getting any error and it is not validating. I am extending it like below,
<input type="checkbox" name="test[]" />x <input type="checkbox" name="test[]" />y <input type="checkbox" name="test[]" />z $("#formid").validate({ rules: { test[]: { required: function(elem) { return $("input.select:checked").length > 0; } }, messages: { test[]: "You must check at least 1 box" } });
To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);
Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.
$('#form1'). submit(function() { if ($('input:checkbox', this).is(':checked') && $('input:radio', this).is(':checked')) { // everything's fine... } else { alert('Please select something! '); return false; } });
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () { $('#formid').validate({ // initialize the plugin rules: { 'test[]': { required: true, maxlength: 2 } }, messages: { 'test[]': { required: "You must check at least 1 box", maxlength: "Check no more than {0} boxes" } } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With