Page 1 of 2 12 LastLast
Results 1 to 10 of 13

Thread: mutlitple checkbox validation

  1. #1
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default mutlitple checkbox validation

    hi all

    i have one form in which i have multiple checkbox options for the user to select.
    i have inserted the validation script in this form which alert the user if the user has not selected any of the checkbox options. if one checkbox is selected then the form will get submit.

    now i want that user should select atleast 4 checkboxes. plz help me with what to change or add in this script.

    the form and javascript validation code is below :

    Code:
    <html>
    <head>
    <script language="javascript">
    
    function validate()
    {
    var chks = document.getElementsByName('colors[]');
    var hasChecked = false;
    for (var i = 0; i < chks.length; i++)
    {
    	if (chks[i].checked)
    	{
    	hasChecked = true;
    	break;
    	}
    }
    
    if (hasChecked == false)
    	{
    	alert("Please select at least one.");
    	return false;
    	}
    
    return true;
    }
    </script>
    
    </head>
    <body>
    <form name="form1" onSubmit="return validate()">
    
    Your colors are <br>
    <input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br> 
    <input type="checkbox" name="colors[]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
    <input type="checkbox" name="colors[]" value="grey" id="grey">grey <br> 
    
    <br>
    <input type="submit" value="submit"  name="submit"/>
    </form>
    </body>
    </html>
    Last edited by jscheuer1; 10-04-2008 at 03:46 AM. Reason: format code

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Check Four - Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    
    <script type="text/javascript">
    function validate(f){
    f = f.elements;
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) alert('Please select at least four.');
    return c > 3;
    };
    </script>
    
    </head>
    <body>
    <form action="#" name="form1" onsubmit="return validate(this)">
    <div>
    Your colors are <br>
    <input type="checkbox" name="colors[1]" value="blue" id="blue">Blue <br> 
    <input type="checkbox" name="colors[2]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[3]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[4]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[5]" value="violet" id="violet">violet <br>
    <input type="checkbox" name="colors[6]" value="gray" id="gray">gray <br> 
    <br>
    <input type="submit" value="submit">
    </div>
    </form>
    </body>
    </html>
    I changed the form and markup so that it would validate. I changed the color input's names to unique values so that in an ordinary server-side situation the individual colors chosen could be retrieved with ordinary GET or POST retrieval methods.
    Last edited by jscheuer1; 10-04-2008 at 03:47 AM. Reason: correct inherited color misspellings 'voilet' & 'grey'
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default multiple checkbox validation

    hi john

    thanks for the reply. your code when tested works fine when run only for javascript.
    but when i inserted in my php form it doesnt works fine.
    If you know php then should i insert the php code here for you to see whats wrong.

    plz reply

    vineet

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I have some limited PHP knowledge. Go ahead and post it. I did say that I changed the names of the color inputs. This is required so that you can GET or POST the data in PHP or other server side code. But it also means that the values you are looking for in the receiving page or process will have these new names. Instead of colors[]=whatever, you will have:

    Code:
    colors[1]=blue
    colors[2]=red
    colors[3]=green
    colors[4]=yellow
    colors[5]=violet
    colors[6]=gray
    Also, I corrected 'grey' and 'voilet' which you had misspelled.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by jscheuer1 View Post
    I have some limited PHP knowledge. Go ahead and post it. I did say that I changed the names of the color inputs. This is required so that you can GET or POST the data in PHP or other server side code. But it also means that the values you are looking for in the receiving page or process will have these new names. Instead of colors[]=whatever, you will have:

    Code:
    colors[1]=blue
    colors[2]=red
    colors[3]=green
    colors[4]=yellow
    colors[5]=violet
    colors[6]=gray
    Also, I corrected 'grey' and 'voilet' which you had misspelled.
    hi john

    The php form and the javascript provided by you is inserted below. please review.

    when i select colors[3][4][5][6], then the result displayed is color green. other 3 colors are not displayed.

    PHP Code:
    <?php
    if(isset($_REQUEST['submit']))
    {
    $user $_REQUEST['fname'];
    $age=$_REQUEST['age'];
    $city=$_REQUEST['city'];
    $gender=$_REQUEST['gender'];

    $colors= array();
    $colors=$_REQUEST['colors'];
    for(
    $i=0;$i<count($colors);$i++)
    {
        
    $selected_colors=$selected_colors $colors[$i] . " , ";
    }

    echo 
    "Hi = " $user "<br>";  
    echo 
    "Your age is = " $age"<br>";
    echo 
    "You Live At = " $city "<br>";
    echo 
    "Your colors are = " $selected_colors "<br>";
    echo 
    "You are " $gender;
    }
    else
    {
    ?>

    <html>
    <head>
    <script type="text/javascript">
    function validate(f){
    f = f.elements;
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) alert('Please select at least four.');
    return c > 3;
    };
    </script>


    </head>
    <body>
    <form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return 

    validate(this)">
    Name : <input type="text" name="fname" />
    <br>
    Age : 
    <input type="text" name="age" />
    <br>
    <br>Choose city : 
    <select name="city">
    <option>select city</option>
    <option value="Chandigarh">Chandigarh</option>
    <option value="calcutta">Calcutta</option>
    <option value="Mumbai">Mumbai</option>
    <option value="Delhi">Delhi</option>
    </select><br>

    Your colors are <br>
    <input type="checkbox" name="colors[1]" value="blue" id="blue">Blue <br> 
    <input type="checkbox" name="colors[2]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[3]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[4]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[5]" value="voilet" id="voilet">voilet <br>
    <input type="checkbox" name="colors[6]" value="grey" id="grey">grey <br> 

    Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" 

    value="Female">Female
    <br>
    <input type="submit" value="submit"  name="submit"/>
    </form>
    </body>
    </html>
    <?php
    }
    ?>
    Last edited by jscheuer1; 10-04-2008 at 08:09 AM. Reason: format code

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I did say that my PHP knowledge was limited. I wasn't aware that a $_REQUEST could be done as an array in the manner your PHP code seems to indicate. If that is the case, and your PHP code was working before, it should be fine to change it back to colors[] for all the color checkboxes. This will also require a slight change in the javascript code:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Check Four - Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    
    <script type="text/javascript">
    function validate(f){
    f = f.elements;
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) alert('Please select at least four.');
    return c > 3;
    };
    </script>
    
    </head>
    <body>
    <form action="#" name="form1" onsubmit="return validate(this)">
    <div>
    Your colors are <br>
    <input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br> 
    <input type="checkbox" name="colors[]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[]" value="violet" id="violet">violet <br>
    <input type="checkbox" name="colors[]" value="gray" id="gray">gray <br> 
    <br>
    <input type="submit" value="submit" name="submit">
    </div>
    </form>
    </body>
    </html>
    Last edited by jscheuer1; 10-04-2008 at 08:55 AM. Reason: add name="submit" back to form - it appears to be required
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default multiple checkbox

    hi john

    thanks very much your code works great.

    tell me one thing that i have to validate 3 more fields (fname,age,city). i have the below validation

    created for them.

    if(document.form1.fname.value == '')
    {
    alert("enter name");
    return false;
    }

    if(document.form1.age.value == '')
    {
    alert("enter age");
    return false;
    }

    if(document.form1.city.value == '')
    {
    alert("enter city");
    return false;
    }

    where should i put this code in your provided function. actually u have mentioned function name as

    function validate(f). i think because of that (f) my other validation code is not working. please clarify

    me how to do.

    thanks
    vineet


    <?php
    if(isset($_REQUEST['submit']))
    {
    $user = $_REQUEST['fname'];
    $age=$_REQUEST['age'];
    $city=$_REQUEST['city'];
    $gender=$_REQUEST['gender'];

    $colors= array();
    $colors=$_REQUEST['colors'];
    for($i=0;$i<count($colors);$i++)
    {
    $selected_colors=$selected_colors . $colors[$i] . " , ";
    }

    echo "Hi = " . $user . "<br>";
    echo "Your age is = " . $age. "<br>";
    echo "You Live At = " . $city . "<br>";
    echo "Your colors are = " . $selected_colors . "<br>";
    echo "You are " . $gender;
    }
    else
    {
    ?>

    <html>
    <head>
    <script type="text/javascript">
    function validate(f){
    f = f.elements;
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) alert('Please select at least four.');
    return c > 3;
    }
    </script>


    </head>
    <body>
    <form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return

    validate(this)">
    Name : <input type="text" name="fname" />
    <br>
    Age :
    <input type="text" name="age" />
    <br>
    <br>Choose city :
    <select name="city">
    <option>select city</option>
    <option value="Chandigarh">Chandigarh</option>
    <option value="calcutta">Calcutta</option>
    <option value="Mumbai">Mumbai</option>
    <option value="Delhi">Delhi</option>
    </select><br>

    Your colors are <br>
    <input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
    <input type="checkbox" name="colors[]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
    <input type="checkbox" name="colors[]" value="grey" id="grey">grey <br>

    Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender"

    value="Female">Female
    <br>
    <input type="submit" value="submit" name="submit"/>
    </form>
    </body>
    </html>
    <?php
    }
    ?>

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    function validate(f){
    f = f.elements;
    var msg = '', colors = function(){
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) msg = '\nPlease select at least four colors.';
    return c > 3;
    }, valid = colors();
    if(f['city'].options.selectedIndex == 0){
    valid = false;
    msg = '\nPlease enter City.' + msg;
    };
    if(f['age'].value == ''){
    valid = false;
    msg = '\nPlease enter Age.' + msg;
    };
    if(f['fname'].value == ''){
    valid = false;
    msg = '\nPlease enter Name.' + msg;
    };
    if(!valid) alert(msg.replace(/^\n/, ''));
    return valid;
    };
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. #9
    Join Date
    Jun 2008
    Posts
    121
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default mutlitple checkbox

    hi john

    all your code worked great.

    i inserted one field [gender] which has two radio buton options male and female. one option is to be selected. the validation applied is

    if(f['gender[0]'].checked == false) || (f['gender[1]'].checked == false){
    valid = false;
    msg = '\nPlease enter gender.' + msg;
    };

    why is it not working. if i comment the gender field validation then everything works fine.

    vineet

    <?php
    if(isset($_REQUEST['submit']))
    {
    $user = $_REQUEST['fname'];
    $age=$_REQUEST['age'];
    $city=$_REQUEST['city'];
    $gender=$_REQUEST['gender'];

    $colors= array();
    $colors=$_REQUEST['colors'];
    for($i=0;$i<count($colors);$i++)
    {
    $selected_colors=$selected_colors . $colors[$i] . " , ";
    }

    echo "Hi = " . $user . "<br>";
    echo "Your age is = " . $age. "<br>";
    echo "You Live At = " . $city . "<br>";
    echo "Your colors are = " . $selected_colors . "<br>";
    echo "You are " . $gender;
    }
    else
    {
    ?>

    <html>
    <head>
    <script type="text/javascript">

    function validate(f){
    f = f.elements;
    var msg = '', colors = function(){
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && /^colors\[\]$/.test(f[i].name) && f[i].checked) ++c;
    if (c < 4) msg = '\nPlease select at least four colors.';
    return c > 3;
    }, valid = colors();
    if(f['city'].options.selectedIndex == 0){
    valid = false;
    msg = '\nPlease enter City.' + msg;
    };
    if(f['age'].value == ''){
    valid = false;
    msg = '\nPlease enter Age.' + msg;
    };
    if(f['fname'].value == ''){
    valid = false;
    msg = '\nPlease enter Name.' + msg;
    };

    if(f['gender[0]'].checked == false) || (f['gender[1]'].checked == false){
    valid = false;
    msg = '\nPlease enter gender.' + msg;
    };

    if(!valid) alert(msg.replace(/^\n/, ''));
    return valid;
    };
    </script>


    </head>
    <body>
    <form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" onSubmit="return validate(this)">
    Name : <input type="text" name="fname" />
    <br>
    Age :
    <input type="text" name="age" />
    <br>
    <br>Choose city :
    <select name="city">
    <option>select city</option>
    <option value="Chandigarh">Chandigarh</option>
    <option value="calcutta">Calcutta</option>
    <option value="Mumbai">Mumbai</option>
    <option value="Delhi">Delhi</option>
    </select><br>

    Your colors are <br>
    <input type="checkbox" name="colors[]" value="blue" id="blue">Blue <br>
    <input type="checkbox" name="colors[]" value="red" id="red">red <br>
    <input type="checkbox" name="colors[]" value="green" id="green">green <br>
    <input type="checkbox" name="colors[]" value="yellow" id="yellow">yellow <br>
    <input type="checkbox" name="colors[]" value="voilet" id="voilet">voilet <br>
    <input type="checkbox" name="colors[]" value="grey" id="grey">grey <br>

    Gender<input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female
    <br>
    <input type="submit" value="submit" name="submit"/>
    </form>
    </body>
    </html>
    <?php
    }
    ?>
    Last edited by vineet; 10-05-2008 at 07:48 AM. Reason: forget something to mention

  10. #10
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    You are using || (logical OR). With a pair of radio buttons, one will always be false, and there is no gender[0] or gender[1]. In javascript, names are literal. Even in PHP, with radio button groups, only the value of the checked radio button is passed, that's why they can all have the same name with no []. Unfortunately, when checking the value in javascript, all radios must be evaluated individually (I do this in a loop). In an unrelated matter I just realized that since I changed all the color input names to 'colors[]', that makes their validation a little simpler. But since they no longer occupy the last position in the form, there are other changes to their validation as well.

    However, at least in the US, it is generally illegal to require a person to disclose his/her gender unless it is needed, like if you are selling clothing, for male or female styles or sizing. But in a case like that, it should be worded as a preference, not as a declaration of gender, for example:

    HTML Code:
    Male or Female sizes?
    <br>
    <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="Female">Female
    You can always ask a person's gender though, it just cannot be required for submission, and therefore should not be validated unless it is a preference, rather than a declaration.

    In any case, here's how to validate those two radio buttons using our function (changes and additions, including ones for colors validation, highlighted):

    Code:
    function validate(f){
    f = f.elements;
    var msg = '', gender = function(){
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && f[i].name == 'gender' && f[i].checked)
    return true;
    msg = '\nPlease Check for Male or Female Sizes.';
    return false;
    }, valid = gender(), colors = function(){
    for (var c = 0, i = f.length - 1; i > -1; --i)
    if (f[i].name && f[i].name == 'colors[]' && f[i].checked) ++c;
    if (c < 4) msg = '\nPlease Select at least Four Colors.' + msg;
    return c > 3;
    };
    valid = colors()? valid : false;
    if(f['city'].options.selectedIndex == 0){
    valid = false;
    msg = '\nPlease enter City.' + msg;
    };
    if(f['age'].value == ''){
    valid = false;
    msg = '\nPlease enter Age.' + msg;
    };
    if(f['fname'].value == ''){
    valid = false;
    msg = '\nPlease enter Name.' + msg;
    };
    if(!valid) alert(msg.replace(/^\n/, ''));
    return valid;
    };
    Last edited by jscheuer1; 10-05-2008 at 09:36 AM. Reason: spelling
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •