Tuesday, 15 January 2013

JQuery Validation for Multiple Checkbox Form | PHP Tutorials For Beginners


Sometime we come to the situation where we want to validate the form with multiple checkbox and at least one checkbox is selected.
In this tutorial of phpcodeforbeginner.blogspot.in we validate form with multiple checkboxes with use of jQuery. The result will return true only if atleast one checkbox is selected.

In below example we create a html page which have multiple checkboxes. When we click on submit a validate() function will get call and it will check how many checkbox is selected. If nothing is selected then it show javascript alert that "nothing is selected" otherwise it show the javascript alert with no of checkbox selected.
It is pretty simple code to validate multiple checkboxes with help of jquery. You can also try validating checkboxes using JavaScript.

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
function validate()
{
         var fields = $("input[name='checkbox']").serializeArray();
         if (fields.length == 0)
        {
              alert('nothing selected');
        }
        else
       {
             alert(fields.length + " items selected");
       }
}
</script>
</head>
<body>
<form action="" method="GET" id="Form">

<div><input name="checkbox" type="checkbox"  value="PHP Tutorial" >Php Tutorial</div>
<div><input name="checkbox" type="checkbox"  value="Javascript" >Javascript</div>
<div><input name="checkbox" type="checkbox"  value="Validation" >Validation</div>

<input name="submit" type="button"  value="submit" onclick="validate();">
</body>
</html>

Hope this jquery form validation for multiple checkboxes tutorial is useful for you. Keep following www.phpcodeforbeginner.blogspot.in for more help.

4 comments:

  1. Good practice to jquery ajax

    ReplyDelete
  2. Good practice to jquery ajax

    ReplyDelete
  3. ive just copied this exact code however when testing it and clicking submit nothing happens, no error message nothing

    i need to check atleast two boxes before they sign up one for charity one for the terms

    any idea if this will work and why its currently not?

    great scripts tho!

    ReplyDelete
    Replies
    1. Hey Kyle thanks for comment. I had forgot to include Jquery source file in head tag. Now I have updated the code, you can try it now.

      Delete