5

I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.

My HTML is:

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
  <link rel='stylesheet' href='stylesheet.css' type='text/css'/>
  <script type='text/javascript' src='script.js'></script>
</head>
<body>
 <form>
  First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
  Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
  Age : <input type='text' id='age' placeholder='Age'><br><br>
  Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
 </form>
 <button id='submit'>Submit</button>
</body>
</html>

My JavaScript/jQuery is:

$(document).ready(function()
{
 var fname = document.getElementById('fname').val();
 var lname = document.getElementById('lname').val();
 var age = document.getElementById('age').val();
 /*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/

  $("#submit").click(function()
  {
   if(fname.length === 0)
   {
    alert("Please input a first name");
   }
   else if(lname.length === 0)
   {
    alert("Please input a last name");
   }
   else if(age.length === 0)
   {
    alert("Please input an age");
   }
  });
});

I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.

Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.

This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.

Thanks!

5 Answers 5

8

You need to use .value instead of .val() since you're using pure Javascript:

var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;

if you want to use .val() method then you need a jQuery object:

var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();

You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:

$(document).ready(function () {
    $("#submit").click(function () {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var age = document.getElementById('age').value;

        if (fname.length == 0) {
            alert("Please input a first name");
        } else if (lname.length == 0) {
            alert("Please input a last name");
        } else if (age.length == 0) {
            alert("Please input an age");
        }
    });
});

Fiddle Demo

Sign up to request clarification or add additional context in comments.

3 Comments

I corrected that but now even if I input the first name it says Please enter a first name.
Did you check my demo? You need to put the variables inside click handler to get the values inside your textboxes in real time. Please check my answer again.
Sorry I didn't look at that. And how do I check if the user has ticked either option in sex or not? I don't know how to handle that. There are two options in the same class of both radio type inputs.
0

from your example, get elements by class name

var lists = document.getElementsByClassName("sex");

to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"

if you use native/pure javascript use .value not val() . val() is only for jquery

1 Comment

I want to check if the user has ticked on any of the two or not.
0

It looks like you're asking a couple questions at once.

As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.

I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.

As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.

Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/

One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.

2 Comments

what does this line mean? (!current.checked && i == (len-1) ?
That's checking two things. First, if we DON'T have a checked radio and we just hit the last element in the list. In other words, we went through the whole list and on the last item, we still don't see a checked radio item.
0

Here is very simple way to make form validation using jquery

// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='registration']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      },
      password: {
        required: true,
        minlength: 5
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",

      password: {
        required: "Please provide a password",
        minlength: "Your password must be at least 5 characters long"
      },
      email: {
        required: "Please provide a valid user name",
        email: "Please enter a valid email address"
      }
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});
@import url("https://fonts.googleapis.com/css?family=Open+Sans");

/* Styles */

* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Open Sans";
  font-size: 14px;
}

.container {
  width: 500px;
  margin: 25px auto;
}

form {
  padding: 20px;
  background: #2c3e50;
  color: #fff;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
}

form label,
form input,
form button {
  border: 0;
  margin-bottom: 3px;
  display: block;
  width: 100%;
}

form input {
  height: 25px;
  line-height: 25px;
  background: #fff;
  color: #000;
  padding: 0 6px;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

form button {
  height: 30px;
  line-height: 30px;
  background: #e67e22;
  color: #fff;
  margin-top: 10px;
  cursor: pointer;
}

label.error {
  color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
  <h2>Registration</h2>
  <form action="" name="registration">
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="[email protected]" />
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="&#9679;&#9679;&#9679;&#9679;&#9679;" />
    <button type="submit">Register</button>
  </form>
</div>

Comments

0
function validate() {
    var scheduledOn = $("#ScheduledOn").val();
    var status = $(".Status option:selected").text();
    var result = true;

    if (id == "") {
        var scheduledOn = $("#ScheduledOn").val();
        var category = $(".categoryList option:selected").text();
        var activityTask = $(".activityTaskList option:selected").text();

        var lead = $("#LeadID").val();
        var agent = $("#AgentID").val();

        if (category == "Select Category") {
            $("#categoryValidation").show();
            $("#categoryValidation").text("The Category field is required");
        }
        else {
            $("#categoryValidation").hide();
        }

        if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
            var activityTask = $(".activityTaskList option:selected").text();

            if (activityTask == "Select Activity Task") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
            }
            else {
                $("#activityTaskValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Joint Field Work") {
            if (lead == "" || lead == null || lead == "Select Lead") {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }

            else {
                $("#leadValidation").hide();
            }
        }

        if (category == "Agent Recruitment" || category == "Agent Development") {
            if (agent == "" || agent == "Select Agent") {
                $("#agentValidation").show();
                $("#agentValidation").text("The Agent field is required");
                result = false;
            }
            else {
                $("#agentValidation").hide();
            }
        }

        if (category == "Direct Sales") {
            if (lead == "" || lead == "Select Lead" || lead == null) {
                $("#leadValidation").show();
                $("#leadValidation").text("The Lead field is required");
                result = false;
            }
            else {
                $("#leadValidation").hide();
            }
        }

        if (scheduledOn == "" || scheduledOn == null) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field is required");
            result = false;
        }
        else if (Date.parse(scheduledOn) <= Date.now()) {
            $("#scheduledOnValidation").show();
            $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
            result = false;
        }
        else {
            $("#scheduledOnValidation").hide();
        }

        return result;
    }
    else {
        var scheduledOn = $("#NewScheduledOn").val();
        var status = $(".Status option:selected").text();

        if (document.getElementById("SetAppointment_Y").checked) {
            var activityTask = $(".activityTaskList").val();

            if (activityTask == null || activityTask == "") {
                $("#activityTaskValidation").show();
                $("#activityTaskValidation").text("The Activity Task field is required");
                result = false;
            }
            else {
                $("#activityTaskValidation").hide();
                $("#scheduledOnValidation").hide();
            }

            if (status != null && (scheduledOn == "" || scheduledOn == null)) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field is required");
                $("#statusValidation").hide();
                result = false;
            }
            else if (Date.parse(scheduledOn) <= Date.now()) {
                $("#scheduledOnValidation").show();
                $("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
                result = false;
            }
            else {
                $("#scheduledOnValidation").hide();
                $("#statusValidation").show();
            }
        }
    }

    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.