go to  ForumEasy.com   
JavaPro  
 
 
   Home  |  MyForum  |  FAQ  |  Archive    You are not logged in. [Login] or [Register]  
Forum Home » JavaScript » Form field validation - verify checkbox using JavaScript
Email To Friend  |   Set Alert To This Topic Rewarding Points Availabe: 0 (What's this) New Topic  |   Post Reply
Author Topic: Form field validation - verify checkbox using JavaScript
WebSpider
member
offline   
 
posts: 147
joined: 06/29/2006
from: Seattle, WA
  posted on: 08/01/2006 09:58:56 PM    Edit  |   Quote  |   Report 
Form field validation - verify checkbox using JavaScript
It is very common to see if a checkbox has been checked or not before a form being sent out to server. This can be done by the following javascript code

<script language="JavaScript">
function verify_checkbox(checkbox)
{
   var isChecked = false;
   if checkbox[0]) { /* chackbox group/array */
	
      for(var j=0; j<checkbox.length; j++){
         if(checkbox[j].checked){
	    alert("The checkbox #"+(j+1)+"has been checked.");
            isChecked = true;
         }
      }
   }else{
      if(checkbox.checked){
         alert("The checkbox has been checked.");
	 isChecked = true; 
      }
   }

   if(!isChecked)
   	alert("No checkbox has been checked.");

}
</script>

What we have learned are:
  • The attribute 'checked' of checkbox plays a key role;
  • There could be an array of checkboxes bearing the same group name.

  •  Profile | Reply Points Earned: 0
    WebSpider
    member
    offline   
     
    posts: 147
    joined: 06/29/2006
    from: Seattle, WA
      posted on: 06/27/2011 06:02:27 PM    Edit  |   Quote  |   Report 
    The corresponding HTML should be as follows.

    <html>
    <body>
    <form onsubmit="return verify_checkbox(this.checkbox);" action="">
        <input type="checkbox" id="checkbox" value="Dog">Dog</p>
        <input type="checkbox" id="checkbox" value="Cat">Cat</p>
        <input type="submit" value="Submit" />
    </form>
    </body>
    </html>
    
     Profile | Reply Points Earned: 0

     
    Powered by ForumEasy © 2003-2005, All Rights Reserved. | Privacy Policy | Terms of Use
     
    Get your own forum today. It's easy and free.