Single / Multiple Checkbox Validation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • infernodeep
    New Member
    • May 2008
    • 3

    Single / Multiple Checkbox Validation

    Hi,

    I have a dynamically generated form, and each listing contains a checkbox named 'del'.
    The users checks the 'del' checkbox next to each listing they wish to delete, and click the submit button. If there are multiple listings/checkboxes on the page, then the script I have works quite well, but if there is only one checkbox displayed on the page. If there is only one checkbox, and the user clicks the submit button, it still submits the form even if the single checkbox is not checked.

    Here is my script:
    Code:
    <SCRIPT language="JavaScript1.2">
    function valDelForm(theForm)
    {
    var filledIn = false;    
    
        // Use the length property to iterate through each Checkbox
        // to determine if a selection has been made
           for (var counter=0; counter<theForm.del.length; counter++)
           if (theForm.del[counter].checked == true){
           filledIn = true;
           
           //else{
           if (theForm.del.checked == true){
           filledIn = true;
           }
          // }
        }
    
           if (filledIn == false){
           alert('Please select a listing to delete!');
           return(false);
        }  
    
     return(true);
    }
    </script>
    This is how the script is called from the opening form tag: onSubmit="retur n valDelForm(this )"
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    If there's only one checkbox, the length will be undefined, so first make a check that length is defined. If not, use the single checkbox validation code, otherwise check all checkboxes.

    Comment

    Working...