Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validation plugin: validate check box

Tags:

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"   }  }); 
like image 355
ram Avatar asked Mar 16 '13 18:03

ram


People also ask

How check if checkbox is checked jQuery?

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);

How do you verify a check box?

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.

How can we make checkbox required field in jQuery?

$('#form1'). submit(function() { if ($('input:checkbox', this).is(':checked') && $('input:radio', this).is(':checked')) { // everything's fine... } else { alert('Please select something! '); return false; } });


1 Answers

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"             }         }     });  }); 
like image 123
Sparky Avatar answered Dec 21 '22 21:12

Sparky