www.webdeveloper.com
Results 1 to 11 of 11

Thread: validate checkboxes

  1. #1
    Join Date
    Oct 2005
    Posts
    6

    validate checkboxes

    I have a group of checkboxes named "list[]". I want to validate that at least one is checked. How can I do this?

  2. #2
    Join Date
    Jun 2007
    Location
    Washington D.C. Metro
    Posts
    76
    Code:
    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    </head>
    <body>
    	<form name="theForm" action="theAction.html">
    		<input type="checkbox" name="list" />
    		<input type="checkbox" name="list" />
    		<input type="checkbox" name="list" />
    		<input type="submit" value="Validate" />
    	</form>
    <script>
    window.onload=function(){
    	var inputs = document.forms.theForm.getElementsByTagName('input'),
    	submitBtn;
    	for (var i=0,len=inputs.length;i<len;i++){
    		if(inputs[i].type == 'submit'){
    			submitBtn = inputs[i];
    		}
    	}
    	submitBtn.onclick = onSubmitClick;
    }
    
    function onSubmitClick(e){
    	e.preventDefault;
    	var theForm = document.forms.theForm;
    	if(atLeastOneCheck(theForm)){
    		theForm.submit();
    	}else {
    		alert('You must check at least one box!');
    	}
    }
    
    function atLeastOneCheck(form){
    	var inputs = document.forms.theForm.getElementsByTagName('input'),
    	valid = false;
    	for (var i=0,len=inputs.length;i<len;i++){
    		if(inputs[i].type == 'checkbox'){
    			if(inputs[i].checked == true){
    				valid = true;
    			}
    		}
    	}
    	return valid;
    }
    
    </script>
    </body>
    </html>

  3. #3
    Join Date
    Dec 2010
    Posts
    207
    Quote Originally Posted by tracy50 View Post
    I have a group of checkboxes named "list[]". I want to validate that at least one is checked. How can I do this?
    In the interests of reusability, it's a good practice to avoid hard-coding element names into functions. Here the checkOne function can be installed for any form and group of checkboxes or radio buttons.
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Check at least one checkbox or radio button</title>
    </head>
    <body>
    <form id='f1' method='post' action=''>
    <p>
     <input type='checkbox' name='list[]'><br>
     <input type='checkbox' name='list[]'><br>
     <input type='checkbox' name='list[]'><br>
     <input type='checkbox' name='list[]'><br>
     <input type='checkbox' name='list[]'><br>
     <input type='submit'>
    </form>
    <script type='text/javascript'>
    
    document.getElementById( 'f1' ).onsubmit = function()
    { 
     return oneChecked( this[ 'list[]' ], 'Check at least one box' );
    }
    
    function oneChecked( group, msg ) /* Check for one selected in a group of checkboxes or radio buttons */
    {
     var ticked = !group.length && group.checked;
     
     for( var i = 0, len = group.length; i < len & !ticked; i++ )
      ticked = group[ i ].checked;
      
     if( !ticked && msg )
      alert( msg ); 
       
     return ticked;  
    }
    
    </script>
    </body>
    </html>


    Q: I found this code...
    A: Then find its author.

  4. #4
    Join Date
    Oct 2005
    Posts
    6
    works awesome. Thanks so much!

  5. #5
    Join Date
    Jun 2007
    Location
    Washington D.C. Metro
    Posts
    76
    I do not understand this syntax:

    Code:
    var ticked = !group.length && group.checked;
    Can you please explain? ty

  6. #6
    Join Date
    Dec 2010
    Posts
    207
    Quote Originally Posted by trandrus View Post
    I do not understand this syntax:

    Code:
    var ticked = !group.length && group.checked;
    Can you please explain? ty
    If there is only one element, the length property does not exist and ticked signifies the single element's state.
    If there is only one element, the loop is not needed and must not iterate.
    length being undefined is treated as false and therefore not < 0.

    The test may be better written like this:
    Code:
    for( var i = 0, len = group.length || 0; !ticked && i < len; i++ )
     ...


    Q: I found this code...
    A: Then find its author.

  7. #7
    Join Date
    Mar 2010
    Posts
    2,803
    Code:
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
            <script type="text/javascript">
                function validateForm(){
                    isCheckboxTicked = false;
                    txtBoxes = document.getElementById('fld1').getElementsByTagName('input');
                    for(i=0; i < txtBoxes.length; i++){
                        if(txtBoxes[i].checked) {
                            isCheckboxTicked = true;
                            i = txtBoxes.length;
                        }
                    }
                    if(!isCheckboxTicked) {
                        alert('Please select at least 1 checkbox');
                    }
                    return isCheckboxTicked;
                }
            </script>
        </head>
        <body>
            <form id="myForm" action="#" method="post" onsubmit="return validateForm()">
                <fieldset id="fld1">
                    <input type="checkbox" name="chk[]" value="" />Checkbox 1
                    <input type="checkbox" name="chk[]" value="" />Checkbox 2
                    <input type="checkbox" name="chk[]" value="" />Checkbox 3
                    <input type="checkbox" name="chk[]" value="" />Checkbox 4
                </fieldset>
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>

  8. #8
    Join Date
    Dec 2010
    Posts
    207
    Code:
      <script type="text/javascript">
                function validateForm(){
                    isCheckboxTicked = false;
                    txtBoxes = document.getElementById('fld1').getElementsByTagName('input');
                    for(i=0; i < txtBoxes.length; i++){
                        if(txtBoxes[i].checked) {
                            isCheckboxTicked = true;
                            i = txtBoxes.length;
                        }
                    }
                    if(!isCheckboxTicked) {
                        alert('Please select at least 1 checkbox');
                    }
                    return isCheckboxTicked;
                }
            </script>
    That function does an excellent job provided that it only has to act on a group of more than one inputs all of which have the same name, and all of which are contained in a fieldset with id "fld1".


    Q: I found this code...
    A: Then find its author.

  9. #9
    Join Date
    Mar 2010
    Posts
    2,803
    Quote Originally Posted by clueful View Post
    That function does an excellent job provided that it only has to act on a group of more than one inputs all of which have the same name, and all of which are contained in a fieldset with id "fld1".
    Not true.

    Did you actually run the code before posting because you don't seem to understand how the function works just by reading the code?

    The function works even if there is only 1 checkbox in the fieldset.

    Code:
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
            <script type="text/javascript">
                function validateForm(){
                    isCheckboxTicked = false;
                    txtBoxes = document.getElementById('fld1').getElementsByTagName('input');
                    for(i=0; i < txtBoxes.length; i++){
                        if(txtBoxes[i].checked) {
                            isCheckboxTicked = true;
                            i = txtBoxes.length;
                        }
                    }
                    if(!isCheckboxTicked) {
                        alert('Please select at least 1 checkbox');
                    }
                    return isCheckboxTicked;
                }
            </script>
        </head>
        <body>
            <form id="myForm" action="#" method="post" onsubmit="return validateForm()">
                <fieldset id="fld1">
                    <input type="checkbox" name="chk[]" value="" />Checkbox 1
                </fieldset>
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>
    Another option to using a fieldset is to use

    Code:
     
    function getElementsByClassName(oElm, strTagName, strClassName){
        var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
        var arrReturnElements = new Array();
        strClassName = strClassName.replace(/\-/g, "\\-");
        var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
        var oElement;
        for(var i=0; i<arrElements.length; i++){
            oElement = arrElements[i];
            if(oRegExp.test(oElement.className)){
                arrReturnElements.push(oElement);
            }
        }
        return (arrReturnElements)
    }
    to get the required inputs and again the function will work on whether getElementsByClassName returns 1 or many elements.
    Last edited by tirna; 01-16-2011 at 09:26 PM.

  10. #10
    Join Date
    Dec 2010
    Posts
    207
    Quote Originally Posted by tirna View Post
    Not true.

    Did you actually run the code before posting because you don't seem to understand how the function works just by reading the code?

    The function works even if there is only 1 checkbox in the fieldset.
    Yes I missed that aspect, but the hazard with that technique is that if someone adds to that fieldset's markup, the collection could inadvertently pick-up unrelated input elements.
    My point is that functions should be coded to be reusable and not committed by hard-coded identifiers.


    Q: I found this code...
    A: Then find its author.

  11. #11
    Join Date
    Mar 2010
    Posts
    2,803
    Quote Originally Posted by clueful View Post
    Yes I missed that aspect, but the hazard with that technique is that if someone adds to that fieldset's markup, the collection could inadvertently pick-up unrelated input elements.
    My point is that functions should be coded to be reusable and not committed by hard-coded identifiers.
    Normally I would use the getElementsByClassName() I posted so additional inputs would not be picked up.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles