How To Handle Form Data With jQuery

How To Handle Form Data With jQuery

The article demonstrates how to handle and validate form data with jQuery. Included are code and examples for name, password, and email fields.

Forms are the common feature of any webpage. Forms are essential in providing user service, user identification, user registration, taking user feedback, and much more. It’s effortless to handle form using jQuery. This article will show how to handle a web form with some operations like collecting data from the form and processing form data. We will learn how to handle any form using jQuery code with a step-by-step breakdown of what the code does when a user submits a form!

Including jQuery With a CDN

First of all, we add the CDN of the jQuery library at the head of the website. If you have the jQuery library already downloaded on your PC, skip this step and include the library. The below code can add the CDN of the library.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

Addionally, for the social icons, we need to add the Font Awesome stylesheet in the header of the webpage too.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css">

Form HTML code

Basic Form Handling With jQuery
Basic Form Handling With jQuery

Above is the form we’ll be working with. The HTML code is the structure of our form. The code for the form, buttons, and fields are given below.

<div class="container right-panel-active" id="container">
  <div class="form-container sign-up-container">
    <form id="signup_form" method="post" action="#">
      <h1>Create Account</h1>
      <div class="social-container">
        <a href="#" class="social"><i class="fab fa-facebook-f"></i></a>
        <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a>
        <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a>
      </div>
      <span>or use your email for registration</span>
      <input id="name" type="text" placeholder="Name" />
      <input id="email" type="email" placeholder="Email" />
      <input id="password" type="password" placeholder="Password" />
      <button>Sign Up</button>
    </form>
  </div>
<!--   <div class="form-container sign-in-container">
    <form action="#">
      <h1>Sign in</h1>
      <div class="social-container">
        <a href="#" class="social"><i class="fab fa-facebook-f"></i></a>
        <a href="#" class="social"><i class="fab fa-google-plus-g"></i></a>
        <a href="#" class="social"><i class="fab fa-linkedin-in"></i></a>
      </div>
      <span>or use your account</span>
      <input type="email" placeholder="Email" />
      <input type="password" placeholder="Password" />
      <a href="#">Forgot your password?</a>
      <button>Sign In</button>
    </form>
  </div> -->
  <div class="overlay-container">
    <div class="overlay">
      <div class="overlay-panel overlay-left">
        <h1>Welcome Back!</h1>
        <p>To keep connected with us please login with your personal info</p>
        <button class="ghost" id="signIn">Sign In</button>
      </div>
      <div class="overlay-panel overlay-right">
        <h1>Hello, Friend!</h1>
        <p>Enter your personal details and start journey with us</p>
        <button class="ghost" id="signUp">Sign Up</button>
      </div>
    </div>
  </div>
</div>

Styling The Form

Below is what the signup form looks like without CSS styles.

Form Without CSS Styles
Form Without CSS Styles

We built the skeleton of the form. Now let’s give it some alignment and an attractive look. The below CSS code will align and provide a beautiful look and feel.

Note: Remember, these codes are not fixed; you can provide your style to the form.

@import url("https://fonts.googleapis.com/css?family=Montserrat:400,800");

* {
  box-sizing: border-box;
}

body {
  background: #f6f5f7;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  font-family: "Montserrat", sans-serif;
  height: 100vh;
  margin: 0;
  background: linear-gradient(white, #d7d7d7);
}

h1 {
  font-weight: bold;
  margin: 0;
}

h2 {
  text-align: center;
}

p {
  font-size: 14px;
  font-weight: 100;
  line-height: 20px;
  letter-spacing: 0.5px;
  margin: 20px 0 30px;
}

span {
  font-size: 12px;
}

a {
  color: #333;
  font-size: 14px;
  text-decoration: none;
  margin: 15px 0;
}

button {
  border-radius: 20px;
  border: 1px solid #2b47ff;
  background-color: #2b49ff;
  color: #ffffff;
  font-size: 12px;
  font-weight: bold;
  padding: 12px 45px;
  letter-spacing: 1px;
  text-transform: uppercase;
  transition: transform 80ms ease-in;
  margin-top: 10px;
}

button:active {
  transform: scale(0.95);
}

button:focus {
  outline: none;
}

button.ghost {
  background-color: transparent;
  border-color: #ffffff;
}

form {
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 0 50px;
  height: 100%;
  text-align: center;
}

input {
  background-color: #eee;
  border: none;
  padding: 12px 15px;
  margin: 8px 0;
  width: 100%;
}

.container {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  position: relative;
  overflow: hidden;
  width: 768px;
  max-width: 100%;
  min-height: 480px;
}

.form-container {
  position: absolute;
  top: 0;
  height: 100%;
  transition: all 0.6s ease-in-out;
}

.sign-in-container {
  left: 0;
  width: 50%;
  z-index: 2;
}

.container.right-panel-active .sign-in-container {
  transform: translateX(100%);
}

.sign-up-container {
  left: 0;
  width: 50%;
  opacity: 0;
  z-index: 1;
}

.container.right-panel-active .sign-up-container {
  transform: translateX(100%);
  opacity: 1;
  z-index: 5;
  animation: show 0.6s;
}

@keyframes show {
  0%,
  49.99% {
    opacity: 0;
    z-index: 1;
  }

  50%,
  100% {
    opacity: 1;
    z-index: 5;
  }
}

.overlay-container {
  position: absolute;
  top: 0;
  left: 50%;
  width: 50%;
  height: 100%;
  overflow: hidden;
  transition: transform 0.6s ease-in-out;
  z-index: 100;
}

.container.right-panel-active .overlay-container {
  transform: translateX(-100%);
}

.overlay {
  background: #ff416c;
  background: -webkit-linear-gradient(to right, #ff4b2b, #ff416c);
  background: linear-gradient(to right, #2b53ff, #0d2234);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 0 0;
  color: #ffffff;
  position: relative;
  left: -100%;
  height: 100%;
  width: 200%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.container.right-panel-active .overlay {
  transform: translateX(50%);
}

.overlay-panel {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 0 40px;
  text-align: center;
  top: 0;
  height: 100%;
  width: 50%;
  transform: translateX(0);
  transition: transform 0.6s ease-in-out;
}

.overlay-left {
  transform: translateX(-20%);
}

.container.right-panel-active .overlay-left {
  transform: translateX(0);
}

.overlay-right {
  right: 0;
  transform: translateX(0);
}

.container.right-panel-active .overlay-right {
  transform: translateX(20%);
}

.social-container {
  margin: 20px 0;
}

.social-container a {
  border: 1px solid #dddddd;
  border-radius: 50%;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 0 5px;
  height: 40px;
  width: 40px;
}

.error {
  height: 20px;
  color: red;
  line-height: 20px;
  text-align: left;
  display: block;
  width: 100%;
}

Now our signup form will look like the image below.

Form With CSS Styles
Form With CSS Styles

The jQuery code

After designing and styling the form using HTML and CSS, it is time to add jQuery functionality. The below code will add field validation and error handling to the form.

$(document).ready(function () {
  
  $("#signup_form").submit(function (e) {
    
    var fromFilled = 0;
    e.preventDefault();
    
    var name = $("#name").val();
    var email = $("#email").val();
    var password = $("#password").val();
    
    $(".error").remove();
    
    // Check the name length, return an error if field is empty.
    if (name.length < 1) {
      $("#name").after(
        '<span class="error">Name is required</span>'
      );
      fromFilled = 1;
      return;
    }
    
    // Check the email length, return an error if the field is empty.
    // Also run a regex against the email to verify the value is an email.
    if (email.length < 1) {
      $("#email").after('<span class="error">Email is required</span>');
      fromFilled = 1;
      return;
    } else {
      var regEx = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      var validEmail = regEx.test(email);
      if (!validEmail) {
        $("#email").after('<span class="error">Enter a valid email</span>');
        fromFilled = 1;
        return;
      }
    }
    
    // Check the length of the password value, if empty return an error. 
    if (password.length < 8) {
      $("#password").after(
        '<span class="error">Password must be at least 8 characters long</span>'
      );
      fromFilled = 1;
      return;
    }
    
    // If form has been filled send the data to a server.
    if (fromFilled == 0) {
      alert(
        "Name : " +
          name +
          "\n" +
          "Email : " +
          email +
          "\n" +
          "DO SOMETHING WITH THE INFORMATION"
      );
      // ADD YOUR CODE TO PROCESS INFO HERE !!!!
    }
  });
});

Breaking Down jQuery

Let’s describe each part of the code using code blocks to understand what is happening in the jQuery form code.

The jQuery ready function allows the code to run only after a fully loaded webpage.

$(document).ready(function() {
 	//CODE HERE
});

The submit function runs whenever a user clicks the submit button.

$('#signup_form').submit(function(e) {
   //CODE HERE
})
;

The formFilled variable will work as a switch. The switch will be declared initially zero. If a user performs any mistakes or forgets to fill any part of the form the variable will switch to one.

var fromFilled = 0;

The jQuery preventDefault cancels the event.

e.preventDefault();

The syntax below is the general format to fetch inputs from a specific HTML element. Below, we have the nameemail, and password variables set as the value from their respective fields using the val() function.

Syntax:

var variableName  = $('#elementID').val();
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();

The remove jQuery function will remove the error HTML element and the error message provided to the user.

$(".error").remove();

The regEx variable is the general regex format for checking the validity of email addresses. Variable validEmail will be false if the email address is invalid.

var regEx = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

var validEmail = regEx.test(email);

Checking the Password Field Is Not Empty in Forms With jQuery
Checking the Password Field Is Not Empty in Forms With jQuery

The name.length if statement checks whether the user entered their name correctly. If the user didn’t fill this field it will show an error message, “Name is required”.

// Check the name length, return an error if field is empty.
if (name.length < 1) {
  $("#name").after(
    '<span class="error">Name is required</span>'
  );
  fromFilled = 1;
  return;
}

The email.length if statement checks whether the user entered his email correctly. If the user didn’t fill this field it will show an error message.

Checking the Email Field Is Not Empty in Forms With jQuery
Checking the Email Field Is Not Empty in Forms With jQuery
// Check the email length, return an error if the field is empty.
if (email.length < 1) {
   $("#email").after('<span class="error">Email is required</span>');
   fromFilled = 1;
   return;
}

The !validEmail if statement checks the validity of the email. If the email is not valid, it will show an error message. The use of variable regEx was described above.

// Also run a regex against the email to verify the value is an email.
if (!validEmail) {
   $("#email").after('<span class="error">Enter a valid email</span>');
   fromFilled = 1;
   return;
}

Checking the Password Field Is Valid in Forms With jQuery
Checking the Password Field Is Valid in Forms With jQuery

The password.length if statement checks whether a user forgot to fill the password field. The code will show an error message if the passsword field is empty.

// Check the length of the password value, if empty return an error.
if (password.length < 8) {
  $("#password").after('<span class="error">Password must be at least 8 characters long</span>'
);
  fromFilled = 1;
  return;
}
Sending Form Data Using jQuery
Sending Form Data Using jQuery

In the last section of the jQuery code, you see an alert function containing the name and the email variable. Usually, this section would prepare and send the form data, and the data is typically sent to a server that handles the new user registration.

// If form has been filled send the data to a server.
if (fromFilled == 0) {
   alert(
     "Name : " +
     name +
     "\n" +
     "Email : " +
     email +
     "\n" +
     "DO SOMETHING WITH THE INFORMATION"
   );
   // ADD YOUR CODE TO PROCESS INFO HERE !!!!
}

All of the functionality, styles, and codes are not fixed. You can change these to fit your needs.

Processing the form data

We have created our form in HTML and provided some attractive look and feel in it using CSS. We then added the necessary functionality using jQuery. Now one thing is left, which is processing that data. There are several ways to process user-provided data, but AJAX is very popular and common. To implement AJAX, we need to create a server script using PHP or PYTHON, receiving that data and sending it to the database.

Conclusion

Now we built our form with the help of jQuery. You can add more functionality to this form and CSS styles to customize this signup form example.

Recommended Articles

Other Articles

Comments

Tip: Thoughtful and well written comments are voted up more often.
0 Comments

No Comments.