Results 1 to 2 of 2

Thread: Javascript checkbox form validation

  1. #1
    Join Date
    May 2008
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Javascript checkbox form validation

    Hi I am trying to validate my webpage which has 2 checkboxes on it. I only want the user to select 1 checkbox and if they do select 2 and click submit then an alert box will appear telling them that they have selected 2 boxes. I have managed to make the above happen by having the alert box appear when the 2 checkboxes are selected however the content of the page still gets submitted and moves onto the next page!! How do I stop the page from getting submitted if an alert box appears? I have added my code below.

    Thank you.


    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

    <script language="JavaScript" type="text/javascript">
    function checkscript() {
    if (document.myform.box1.checked == true && document.myform.box2.checked == true)
    { alert('box1 & 2 are selected');
    form.email.focus();
    return false ;
    }

    // If the script makes it to here, everything is OK,
    // so you can submit the form

    else return true;
    }

    </script>
    </head>

    <body>

    <form name="myform" action="page.html" method="post" onsubmit="return checkscript()">


    <input
    type="checkbox"
    name="box1"
    value="yes1">
    <input
    type="checkbox"
    name="box2"
    value="yes2">
    <input
    type="submit">
    </form>
    </body>
    </html>

  2. #2
    Join Date
    Feb 2008
    Location
    Cebu City Philippines
    Posts
    1,160
    Thanks
    17
    Thanked 277 Times in 275 Posts

    Default

    language is a deprecated attribute, type will suffice.

    See if removing the highlighted helps:
    Code:
    <script language="JavaScript" type="text/javascript">
    function checkscript() {
    if (document.myform.box1.checked == true && document.myform.box2.checked == true)
    { alert('box1 & 2 are selected');
    // form.email.focus(); this part is erroeneous
    return false ;
    }
    
    // If the script makes it to here, everything is OK,
    // so you can submit the form
    
    else return true;
    }
    
    </script>
    Learn how to code at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph!

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
  •