Click here to Skip to main content
13,594,513 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.5K views
1 bookmarked
Posted 5 Oct 2015
Licenced CPOL

Making a Basic Application using a JQuery Validation plug in

, 1 Mar 2016
Rate this:
Please Sign up or sign in to vote.
Making Your First App using a JQuery Plugin

Introduction

I am upgrading this article as I was deplete of some of the depth this article and it code needed.  I added further to this some better formatting and some customized messaging.  The additions have been made to the CSS JQuery and HTML.  I hope the second edition has a little more clarity and help than the first. 

Background

  I have just been getting to grips with JQuery and JavaScript, and found it rather handy the libraries that have been wrote for communal usage.  This programme is an attempt to use the JQuery validate library.  The main difference this time is I used it to work on when the submit button is clicked as opposed to be ran after an event before submit.

 An accountancy programmed was the first programme I wrote when learning programming and I tend to write them a lot as on a basic level(accountancy) they are easy to write and debug, on the business and logic end.

Using the code

This is a single page HTML app with some JQuery script in the head that calculates a total and a ratio.  The basics of the app is for a beginner to write a small piece of code that can be validated and when validated it will give a result. 

 

Below is the basic reference and titling for the site. I call Bootstrap, the core JQuery library and a validation plugin, plus my own styling sheet.

<!DOCTYPE html>
<html>
<head>
<title>
Accounting Work

</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>

<link rel ="stylesheet" href="exp.css">

 I start off with the .click event and this will be one of two event that will perform actions.  After the click the  JQuery Validation plugin(see bold text)  is called to set the criteria form what is valid input.  In the case of the example I consider valid input that is required, numeric a minimum length and a maximum length of 12.  The plug in also gives one the chance to customize messages.

  So after I have set the validation criteria we use the .valid() from the plugin to check if the form passes as valid. The validate method gives one a chance to pass back a Boolean on whether the form is valid or not. If the dta is valid we are left with the number to utilize the Accountancy Code. 

After I finish the Maths I have an else statement that can pass back a boolean or give an alert message to why the Form is not Valid at present.

The next part of the code is a reset button which clears the form and the two text boxes with the result.  On the form we have used the JavaScript to validate that the data in our input meets a set criteria, if not we make the user aware the standard is not met.  Secondly we us the java script to do some basic baths and format the numbers to two decimal places by using the .toFixed Method and the .parseFloat method respectively.

<script>
$(document).ready(function() {
$("#submitReturn").click(function()

{
    // set my validation rules up to haver maxlength and all input to be numeric
   $( "#myappform" ).validate({
        rules:    {
                    gsSales:{
                            required: true,
                            minlength: 1,
                            number: true,
                            maxlength: 12,
                            
                            },
        messages:     {
             gsSales:{
                required: function(){return $("#errLabel1").text("Gross Sales is a Required Field!");},
                number:function(){return $("#errLabel1").text("Gross Sales requires A Numeric Entry!");                      }
                     }

// There are 5 more pieces of code for the validation wrote but the code is identical for all so to save space I have left it off.
                  }
});

   if ($("#myappform").valid())
    // if my input is valid proceed
    {  
         var gs = parseFloat($("#gsTxt").val(), 10);

     }

        var sc = os + ps - cs - mr;
        
        // net sales calculation
        var ts = gs - cr;
        // ratio calculataion
        var gpr = (((ts - sc)/ ts) * 100);
        
        // placing the calculated values to the thext boxes in the ratio and totakl section
        
        $("#gsPrft").val((ts - sc).toFixed(2));
        
        $("#gsPrfRto").val(gpr.toFixed(2) + "%");


    }
    else
    {
    //if not valid place error message 
    alert("error in form");
    }
    });

    // my reset button to clear the form and the two boxes which carry the calculated values.
    $("#clearValues").click(function()
    
    {
        alert("clearing the form");
        $(":input", "#myappform")
            .not(":button, :submit, :reset")
            .val('');
        $("#gsPrft").val("");
        $("#gsPrfRto").val("");
        
    }
    );
});

</script>
</head>

//  

HTML

  The HTML is rather simple with just two tables  for the input boxes and the answer boxes, and a form. The reason for the tables is that the table structure formats the input boxes rather neatly. The reason for the form structure is for use with JQuery or a back end  language if that might be the case. In the JQuery code the form variable is used for the validation. 

 

<body>
<h1>A JS Application for Accounting</center></h1>
<div id ="entry">

    <h1>Totals for Calculations</h1>
    
    <form id="myappform" >
    <table id ="table1">
        <tr>
            <td align ="right">Gross Sales:</td>
            <td><input name="gsSales" class="required" id ="gsTxt" /></td>
            <td><p id="errLabel1" class ="eVal"></p></td>
        </tr>
        <tr>
           <td align ="right">Customer Returns:</td>
           <td><input name = "custRet" class ="required" id="crTxt"></td>
           <td><p id="errLabel2" class ="eVal"></p></td>
        </tr>
        <tr>
            <td align ="right">Opening Stock:</td>
            <td><input name= "openStck" class = "required" id ="osTxt"></td>
            <td><p id="errLabel3" class ="eVal"></p></td>
        </tr>
        <tr>
            <td align ="right">Purchased Stock:</td>
            <td><input name = "purchStock" class = "required" id ="psTxt"></td>
            <td><p id="errLabel4" class ="eVal"></p></td>
        </tr>
        <tr>
            <td align ="right">Closing Stock:</td>
            <td><input name = "closStck" class = "required" id="csTxt"></td>
            <td><p id="errLabel5" class ="eVal"></p></td>
        </tr>
        <tr>
            <td align ="right">Merchant Returns:</td>
            <td><input name = "merchRet" class = "required" id ="mrTxt"></td>
            <td><p id="errLabel6" class ="eVal"></p></td>
        </tr>
        
        <tr>
            <td>
                <input type="submit" value="Submit" onclick="getNumbers()" id= "submitReturn" />
                    &nbsp;
                <input type="reset" value="Reset" id= "clearValues" />
            </td>
        </tr>
    </table>
    </form>
    <br>

</div>

</body>
</html>
CSS
The CCS has nothing special other than a stock image from a Google search, and the corresponding code to make sure the background is  just one Image stretched proportionately across the body.  I also have made an error class for the error label as well as some formatting for the tables.
    
body{
    background: url(http://us.123rf.com/450wm/fasphotographic/fasphotographic1302/fasphotographic130200007/17991362-accountancy.jpg)no-repeat center center fixed;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
    text-align: center;
}
#table1
{
    margin: 0 auto;
    text-align: left;
}


#table2
{
    margin: 0 auto;
    text-align: left;
}
.eVal{
    font-family: ligurnio;
    color: #ff0000;
}

 

 

Points of Interest

I was trying to make a form and a use some basic validation with it. Across my web searches I found bits and pieces, or smaller fragments of code.  I placed all the fragments together and made this small App.  All of this code can be found here http://jqueryvalidation.org/ with some useful examples.  I have just used enhnaced htese examples to make a more real life application.

History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

MarcusCole092076
Software Developer (Junior) ABB
United States United States
On career 2.0 mainly work in the dot net environment predominantly SQL and SSMS.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionYou are still using HTML3 instead of HTML5 Pin
Gerd Wagner6-Oct-15 3:02
professionalGerd Wagner6-Oct-15 3:02 
AnswerRe: You are still using HTML3 isntead of HTML5 Pin
MarcusCole0920766-Oct-15 3:33
professionalMarcusCole0920766-Oct-15 3:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03-2016 | 2.8.180621.3 | Last Updated 1 Mar 2016
Article Copyright 2015 by MarcusCole092076
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid