2

I am implementing a simple registration form. I want to validate if the user has selected at least one checkbox. All the fields in my form are being validated without page reload except for this one input field. When I try to validate this field, the page reloads and all the values that the user previously entered are lost. I want to prevent this from happening.

    function validate() {

    var checkbox1 = document.getElementById('three').checked;
    var checkbox2 = document.getElementById('four').checked;
    var checkbox3 = document.getElementById('five').checked;
    var checkbox4 = document.getElementById('six').checked;

    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
            alert("Please enter all the required values");
        } 
    } 

    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
            alert("Please enter all the required values");
        } 
    } 

    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
            alert("Please enter all the required values");
        }  
    } 

    if (document.getElementById('values').value == -1) {
        alert("Please enter all the required values checkbox");
    }
}
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");

#labels{
    position: relative;
    width: 250px;
    float: left;
}

h3{
    margin: 0px 0px 20px 0px;
}

#fields{
    position: relative;
    width: 250px;
    float: left;
}

.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.different{
    margin-top: 4px;
    margin-bottom: 22px;
}

.values{
    margin-bottom: 23px;
}

.heading, .feedback{
    margin-top: 43px;
}

.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}

textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

a{
    color: #06a3e9;
}

.final{
    margin-top: 15px;
}

.feedback{
    margin-top: 73px;
}

#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}

input[type="checkbox"]{
    display: none;
}

label:before{
    width: 1em;
    display: inline-block;
}

label{
    margin-right: 5px;
}

input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}

input[type="checkbox"]:checked + label:before{
    content:"\f14a";
    display: inline-block;
    color: #06a3e9;
}

input[type="radio"]{
    display: none;
}

input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"\f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}

input[type="radio"]:checked + label:before{
    content:"\f192";
    font-size: 14px;
    display: inline-block;
}
<!doctype html>
<html>

  <head>
    <title> Register here </title>
    <link rel="stylesheet" href="../css/registration.css"/>
    <script src = "../javascript/registration.js"></script>
  </head>

  <body>
        <h1>Event Registration Form</h1>

        <div id="labels">
            <h3>Username</h3>
            <h3>Password</h3>
            <h3>Age</h3>
            <h3>Email</h3>
            <h3>Existing customer?</h3>
            <h3>Select your preferences</h3>
            <h3>Newsletter Preferences</h3>
            <h3 class="heading">Menu Options</h3>
            <h3 class="feedback">Send us your feedback !</h3>
        </div>

        <div id="fields">
            <form action="#" method="get" name="referenceToForm">
                <input type="text" name="Username" id="Username" class="element"required/>
                <input type="password" name="Password" class="element" required/>
                <input type="number" name="Age" class="element" required/>
                <input type="email" name="Email" class="element" required/>

            <div class="different">
              <input type="radio" name="customer" id="one" checked="checked" />
              <label for="one">Yes</label>
              <input type="radio" name="customer" id="two" />
              <label for="two">No</label>
            </div>

            <div class="values">
              <input type="checkbox" name="interest" id="three" />
              <label for="three">Dog</label>
              <input type="checkbox" name="interest" id="four" />
              <label for="four">Cat</label>
              <input type="checkbox" name="interest" id="five" />
              <label for="five">Parrot</label>
              <input type="checkbox" name="interest" id="six" />
              <label for="six">Possum</label>
              <span id="spanning"> </span>
            </div>

            <select class="preference" id="preference" value="-1">
                <option value="Entertainment">Entertainment</option>
                <option value="Technology">Technology</option>
                <option value="TV">TV</option>
            </select>
        
            <div class="menu">
                <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                    <option value="Sports">Sports</option>
                    <option value="Politics">Politics</option>
                    <option value="News">News</option>
                    <option value="Swimming">Swimming</option>
                    <option value="Health">Health</option>
                </select>
            </div>
        
            <textarea rows="5" cols="20" required></textarea>
        
            <div class="final">
                <input type="submit" name="submit" id="submit" onclick="validate()" />
                <input type="reset" name="reset" id="reset" />
            </div>
      </form>
    </div>
  </body>
</html>

UPDATE

Thanks to everyone who tried to help me with this. Below is the code which solves my problem perfectly.

function validate() {

    

    var checkbox1 = document.getElementById('three').checked;
        var checkbox2 = document.getElementById('four').checked;
        var checkbox3 = document.getElementById('five').checked;
        var checkbox4 = document.getElementById('six').checked;
    
        if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
                alert("Please enter all the required values");
                return false;
        } 
    }
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
    
    #labels{
        position: relative;
        width: 250px;
        float: left;
    }
    
    h3{
        margin: 0px 0px 20px 0px;
    }
    
    #fields{
        position: relative;
        width: 250px;
        float: left;
    }
    
    .element{
        margin-bottom: 23px;
        border: 1px solid #dadada;
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    .different{
        margin-top: 4px;
        margin-bottom: 22px;
    }
    
    .values{
        margin-bottom: 23px;
    }
    
    .heading, .feedback{
        margin-top: 43px;
    }
    
    .preference{
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    .multiple{
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
        margin-top: 20px;
    }
    
    textarea{
        margin-top: 20px;
        border: 1px solid  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    a{
        color: #06a3e9;
    }
    
    .final{
        margin-top: 15px;
    }
    
    .feedback{
        margin-top: 73px;
    }
    
    #submit, #reset{
        border: 1px solid #dadada;
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
        border-radius:5px;
    }
    
    input[type="checkbox"]{
        display: none;
    }
    
    label:before{
        width: 1em;
        display: inline-block;
    }
    
    label{
        margin-right: 5px;
    }
    
    input[type="checkbox"] + label:before{
        font-family: FontAwesome;
        display: inline-block;
        content: "\f096";
        letter-spacing: 5px;
        color: #06a3e9;
        display: inline-block;
    }
    
    input[type="checkbox"]:checked + label:before{
        content:"\f14a";
        display: inline-block;
        color: #06a3e9;
    }
    
    input[type="radio"]{
        display: none;
    }
    
    input[type="radio"] + label:before{
        font-family: FontAwesome;
        display: inline-block;
        content:"\f10c";
        font-size: 14px;
        color: #06a3e9;
        letter-spacing: 5px;
        display: inline-block;
    }
    
    input[type="radio"]:checked + label:before{
        content:"\f192";
        font-size: 14px;
        display: inline-block;
    }
<!doctype html>
    <html>
    
      <head>
        <title> Register here </title>
        <link rel="stylesheet" href="../css/registration.css"/>
        <script src = "../javascript/registration.js"></script>
      </head>
    
      <body>
            <h1>Event Registration Form</h1>
    
            <div id="labels">
                <h3>Username</h3>
                <h3>Password</h3>
                <h3>Age</h3>
                <h3>Email</h3>
                <h3>Existing customer?</h3>
                <h3>Select your preferences</h3>
                <h3>Newsletter Preferences</h3>
                <h3 class="heading">Menu Options</h3>
                <h3 class="feedback">Send us your feedback !</h3>
            </div>
    
            <div id="fields">
                <form action="#" method="get" name="referenceToForm">
                    <input type="text" name="Username" id="Username" class="element"required/>
                    <input type="password" name="Password" class="element" required/>
                    <input type="number" name="Age" class="element" required/>
                    <input type="email" name="Email" class="element" required/>
    
                <div class="different">
                  <input type="radio" name="customer" id="one" checked="checked" />
                  <label for="one">Yes</label>
                  <input type="radio" name="customer" id="two" />
                  <label for="two">No</label>
                </div>
    
                <div class="values">
                  <input type="checkbox" name="interest" id="three" />
                  <label for="three">Dog</label>
                  <input type="checkbox" name="interest" id="four" />
                  <label for="four">Cat</label>
                  <input type="checkbox" name="interest" id="five" />
                  <label for="five">Parrot</label>
                  <input type="checkbox" name="interest" id="six" />
                  <label for="six">Possum</label>
                  <span id="spanning"> </span>
                </div>
    
                <select class="preference" id="preference" value="-1">
                    <option value="Entertainment">Entertainment</option>
                    <option value="Technology">Technology</option>
                    <option value="TV">TV</option>
                </select>
            
                <div class="menu">
                    <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                        <option value="Sports">Sports</option>
                        <option value="Politics">Politics</option>
                        <option value="News">News</option>
                        <option value="Swimming">Swimming</option>
                        <option value="Health">Health</option>
                    </select>
                </div>
            
                <textarea rows="5" cols="20" required></textarea>
            
                <div class="final">
                    <input type="submit" name="submit" id="submit" onclick="return validate()" />
                    <input type="reset" name="reset" id="reset" />
                </div>
          </form>
        </div>
      </body>
    </html>
Gijzy
  • 102
  • 9
user3421311
  • 171
  • 2
  • 10
  • 1
    see this answer: http://stackoverflow.com/questions/15360094/angularjs-dropdown-required-validation – Erez Haim May 19 '15 at 22:58
  • On a side note, I'd suggest you use some sort of validation script and not reinvent the wheel, like if you are using Jquery this one has proved quiet handy for me. http://bojanmauser.from.hr/bvalidator/ – Mohd Abdul Mujib May 19 '15 at 23:16
  • I think this is an easy fix. Add
    in your form tag and return either true or false. And you can remove the onclick handler in your submit button. Give it a try and let us know.
    – Yogi May 19 '15 at 23:21
  • @ErezHaim That wasn't really helpful. It is probably because I have never worked with Angular. Thanks anyways. – user3421311 May 19 '15 at 23:27
  • 1
    @9kSoft That was helpful. However, I want to learn how to use core JavaScript to validate a form and that's the reason I doing it this way. – user3421311 May 19 '15 at 23:30
  • @Robert I already tried that, but could not get it to work. – user3421311 May 19 '15 at 23:30
  • I failed to understand your question then, can you explain what is it that you want to validate? You want to check in your validate function if user had selected one of the options from dropdown list? – Erez Haim May 19 '15 at 23:32
  • 1
    @user3421311 Ok, if you are doing it for learning then its ok, what I thought was if you are on a deadline for your project, then wasting your time fiddling with front end validation (which is nothing more than a UI frill, and with no security ever) would be something that you would wanna avoid. Just my thought. ;) – Mohd Abdul Mujib May 19 '15 at 23:38
  • @ErezHaim I want to validate if the user has selected one of the `checkboxes` and one of the `options` from the multiple `select` menu. All the fields in my form are being validated without the page getting refreshed except for these two `input` fields. – user3421311 May 19 '15 at 23:38
  • @9kSoft Yes. Thanks for commenting. I did not know such jQuery plugins existed. – user3421311 May 19 '15 at 23:42
  • 1
    @user3421311, You could modify the `required` attribute whenever a checkbox changes to be `true` or `false` depending. That way you still use the native form validation. – redbmk May 20 '15 at 00:00
  • You probably want to run a `event.preventDefault()` when the form is submitted, this will prevent the action from reloading the page. In this case you only want to run it when the validation fails. – Bankzilla May 20 '15 at 00:10
  • Can you explain better about the 2 inputs not validating? Do you mean you are unable to check those inputs in the validation function? – Yogi May 20 '15 at 00:10
  • @redbmk That is a good point, but I do not think that is possible. I say this because `required = false` is being treated in the same way as `required`. See this http://www.w3schools.com/tags/att_input_required.asp for more details. – user3421311 May 20 '15 at 00:35
  • @Robert I am able to validate the inputs, but the page is reloading if I do not do it natively. Due to this reason, values that the user entered are being lost. I want to prevent this from happening. I figured out how to solve this problem for the multiple select menu. Now I just need help with the checkbox input. – user3421311 May 20 '15 at 00:47
  • @user3421311, you could do either `node.required = true` or `node.removeAttribute("required")`. – redbmk May 20 '15 at 01:42

2 Answers2

1

I've spotted 2 problems with your form and both are easy to fix.

Your validation function must return either true to submit the form or false to cancel. If you don't supply a return value, as in your code, the form will always be submitted:

<input type="submit" name="submit" id="submit" onclick="validate()" >

To fix this you need to have your validation function return a value which is returned to the onclick handler:

<input type="submit" name="submit" id="submit" onclick="return validate()" >

This line in the validation function throws an error because there are no elements with id="values". You will need to remove or fix this code so that your function completes normally and returns either a true or false value.

if (document.getElementById('values').value == -1) {
    alert("Please enter all the required values checkbox");
}

Perhaps someone can comment on this, but I've always seen validation handled in the form onsubmit event rather than the submit button onclick event. Yet, perhaps this is just convention as it appears to work either way:

<form onsubmit="return validate()" ...

<input type="submit" onclick="return validate()" ...
Yogi
  • 6,241
  • 3
  • 24
  • 30
0

The main thing, if you are using jsFiddle, is to use this method of initializing functions:

window.validate = function() {

and not like this:

function validate() {

Here is my stab at it. No Angular, nor JQuery used, although I recommend learning each of them. I messed up your submit button, but its easily fixed with css. I also added a fake submit button which triggers the verification only. If it passes verification, then it can continue to send. My jsfiddle:

http://jsfiddle.net/omikey/tfk7d3ks/

<div class="container">
 <div id="labels">
        <h3>Username </h3>
        <h3>Password</h3>
        <h3>Age</h3>
        <h3>Email</h3>
        <h3>Existing customer?</h3>
        <h3>Select your preferences</h3>
        <h3>Newsletter Preferences</h3>
        <h3 class="heading">Menu Options</h3>
        <h3 class="feedback">Send us your feedback !</h3>
     </div>

    <div id="fields">
      <form action="#" method="get" name="referenceToForm">
        <div>
          <input type="text" name="Username" id="Username" class="element" required/>
        </div>
        <div>
          <input type="password" name="Password" class="element" required/>
        </div>
        <div>
          <input type="number" name="Age" class="element" required/>
        </div>
        <div>
          <input type="email" name="Email" class="element" required/>
        </div>
        <div class="different">
          <input type="radio" name="customer" id="one" checked="checked" />
          <label for="one">Yes</label>
          <input type="radio" name="customer" id="two" />
          <label for="two">No</label>
        </div>

        <div class="value">
          <input type="checkbox" name="interest" id="three" />
          <label for="three">Dog</label>
          <input type="checkbox" name="interest" id="four" />
          <label for="four">Cat</label>
          <input type="checkbox" name="interest" id="five" />
          <label for="five">Parrot</label>
          <input type="checkbox" name="interest" id="six" />
          <label for="six">Possum</label>
          <span id="spanning"> </span>
        </div>

        <div>
          <select class="preference" id="preference" value="-1">
            <option value="Entertainment">Entertainment</option>
            <option value="Technology">Technology</option>
            <option value="TV">TV</option>
          </select>
        </div>

        <div class="menu">
          <select multiple id="multiple" class="multiple" value="-1" name="usrgrp[]">
            <option value="Sports">Sports</option>
            <option value="Politics">Politics</option>
            <option value="News">News</option>
            <option value="Swimming">Swimming</option>
            <option value="Health">Health</option>
          </select>
          <span id="spanElement"> </span>
        </div>

        <div class="comment">
          <textarea rows="5" cols="20" required></textarea>
        </div>

        <div class="final">
            <input type="button" name="verify" onclick="validate()" />
          <input type="submit" name="submit" style="display:none" id="submit" />
          <input type="reset" name="reset" id="reset" />
        </div>
      </form>
    </div>
</div>
    @import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");

.container{
    width: 100%;
    margin-left: 400px;
}

#spanning{
    color: #06a3e9;
}

.nav ul{
    width: 150px;
    float: left;
    background-color: #dadada;
    padding: 0px;
    margin: 0px;
}

.nav li{
    list-style-type: none;
}

.nav a{
    color:#000;
    cursor:pointer;
    display: block;
    line-height: 40px;
    text-indent: 10px;
    text-decoration: none;
    font-weight: bold;
}

.nav ul ul li{
    display: none;
}

.nav li:hover ul li{
    display: block;
}

.subnav ul{
    position: relative;
    background: #dadada;

}

#labels{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}

h3{
    margin: 0px 0px 20px 0px;
}

#fields{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}

.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.different{
    margin-top: 4px;
    margin-bottom: 22px;
}

.value{
    margin-bottom: 23px;
}

.heading, .feedback{
    margin-top: 43px;
}

.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}

textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}

a{
    color: #06a3e9;
}

.final{
    margin-top: 15px;
}

.feedback{
    margin-top: 73px;
}

#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}

input[type="checkbox"]{
    display: none;
}

label:before{
    width: 1em;
    display: inline-block;
}

label{
    margin-right: 5px;
}

input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "\f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}

input[type="checkbox"]:checked + label:before{
    content:"\f14a";
    display: inline-block;
    color: #06a3e9;
}

input[type="radio"]{
    display: none;
}

input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"\f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}

input[type="radio"]:checked + label:before{
    content:"\f192";
    font-size: 14px;
    display: inline-block;
}

    window.validate = function() {

    var valid = true;

  var checkbox1 = document.getElementById('three').checked;
  var checkbox2 = document.getElementById('four').checked;
  var checkbox3 = document.getElementById('five').checked;
  var checkbox4 = document.getElementById('six').checked;

  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }    

    if (document.getElementById('multiple').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }

    if (document.getElementById('preference').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }

    if (valid)
    {
        document.getElementById('submit').click();
    }
}
omikes
  • 8,064
  • 8
  • 37
  • 50
  • That was very helpful, but the button is not doing anything after all the fields are filled. It is displaying the alert box when at least one field is empty, so that part of the functionality is working fine. – user3421311 May 20 '15 at 01:35
  • Thanks. That was really helpful, but the page is still reloading if the user checks checkboxes at the end. I mean if we click the submit button after filling the form in the following order: username, password, age, email, existing customer, newsletter preferences, menu options, send us your feedback; the alert box does not pop up and it submits the form letting the user register without checking at least one checkbox. – user3421311 May 20 '15 at 03:41
  • I see what it was, check this out: http://jsfiddle.net/omikey/tfk7d3ks/8 So basically the if statements you wrote for the checkboxes were all checking the same thing. Now there is one if statement which checks if any box is checked, if not the form is invalid. – omikes May 20 '15 at 07:40
  • 1
    That was really helpful. Can you please explain what your eventFire method is doing ? – user3421311 May 20 '15 at 13:21
  • EventFire, as you can see, it takes in two parameters, el and etype; These are short for 'dom element' and 'event type' respectfully. The first if statement, my best guess is that it fires the specified 'event type' (e.g. mouseover, click, etc.) on some older browsers I can't test. In the else statement though, first an 'event object' called evObj is created and arbitrarily named 'Events'. Event objects are required to simulate events such as clicking, which is useful in our case (our submit button is hidden). Finally, this object is dispatched onto the hidden submit provided to the method. – omikes May 20 '15 at 17:50