Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Checkbox validation problem

    Hi!

    I am currently new to javascript and I have a little problem with a code to make sure at leat 1 checkbox is selected in an html form.

    The problem is if no checkbox is selected. The scripts correcly displays an alert but If we click on OK on the alert then the form is sent through (shouln't be)

    Here is the javascript code I have :

    Code:
    <script>
        function doUpdate(){  
            var c = document.getElementsByTagName('input');   
            for (var i = 0; i < c.length; i++) {   
            if (c[i].type == 'checkbox' && c[i].checked == true) {   
            // At least one checkbox IS checked       
            document.form1.submit();    
            return true;   
          }   
        }   
        // Nothing has been checked   
        alert("Please select at least one event");   
        return false;   
        }   
    </script>
    Here is the html form :

    Code:
    <form>
    <input type="checkbox" name="event10" value="1">
    <input type="checkbox" name="event11" value="2">
    <input type="checkbox" name="event12" value="3">
    <input type="checkbox" name="event13" value="4>
    <input type="submit" class="register" onclick="doUpdate()" value="" />
    </form>
    If anyone can help me out it would be really appreciated!!

    Thanks!

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,731
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    onclick="return doUpdate()"

    Note that alerts are regarded as obsolete. Use DOM methods to display a message to your users

    You must also assign an id to our form e.g. <form id = "form1"> and specify the action of the form (the url it submits to)
    and then
    document.getElementById("form1").submit();


    They are gulping in oxygen through every orifice, let me tell you. - Commentator Radio 5 Live
    Last edited by Philip M; 09-04-2013 at 06:48 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    rollinmedia (09-04-2013)

  • #3
    New to the CF scene
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Works perfectly! Thank you so much!


  •  

    Posting Permissions

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