Check if the input (mandatory) field is filled or empty using jquery

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

In this section we are going to see how to check whether the fields(mandatory) are filled by user before further action ,to be more clear let us say there are lots of input fields to get the detail from user and we also have a submit button to submit the details to the cloud for further processes .
So let’s create a jquery plugin for this purpose, but why plugin,the answer is simple we need to reuse the same code in lots of our projects .


Code for html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

<html xmlns="">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<meta content="width=device-width, user-scalable=no" name="viewport">

<meta content="black" name="apple-mobile-web-app-status-bar-style">

<meta name="apple-mobile-web-app-capable" content="yes" />





<div id="demo">

<label>Name</label><input id="user_name" name="User Name" value="" /><br />

<label>Address</label><input id="user_address" name="User Address" value="" />

<input type="submit" id="asd" value="Submit"/>





Here when you look at the html code you would notice the class name for the input values –backme
We have used it so that we can help out our jquery plugin to find the elements on which the function has to be applied for the desired output, nothing else to describe in the html part.

Code for script:


<script type=”text/javascript” charset=”utf-8″>

$(document).ready(function() {






console.log(“All fields entered”);


//submit json to ajax




console.log(“some fields are blank”);

//call error function





var a=0;

var valid=0;

var obj = {};

(function($) {

$.fn.stingme = function() {


return this.each( function() {

var key=$( this ).attr(“id”).trim();


console.log(“valid” +valid);


{ obj[key] = $(“#”+key).val();

// console.log(“valid1” +valid);




{ //console.log(“valid2” +valid);

alert(“Please Enter value for -“+$(‘#’+key).attr(‘name’));


//can highlight the particular field










We will now analyze the script part,
Whenever the submit button is clicked we call a function
Which in turn checks whether the input fields with classname –backme is filled or empty,if any of the field with classname -backme is empty then it shows an alert box indicating that the particular field is empty please fill it to continue.
To be user readability the alert message states that –Please Enter value for -User Name


If you note the click function you ld have come across the line $(“.backme”).stingme();
The above line means that we are binding the plugin named stingme with the elements having the class name backme.
That’s all folks happy coding.

Working plunker link:

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather