Thursday 13 April 2017

Simple Input Validation using JQuery

Good day, dear reader! In this tutorial, I am going to explain to you how to do a simple validation of user input using a JavaScript Library (JQuery). Please note that in this tutorial, I may use this word often: JS, what it means is JavaScript. Pardon me.

JQuery makes writing JavaScript easier, in my own understanding at least, I find it easier writing JQuery to writing plain JavaScript. Take for example:
Plain JS:
document.getElementById('jumbo');

JQuery:
$("#jumbo");

These two lines mean the same thing, but as you can see, JQuery is easier to write and relatively faster, though as some developers have said when I asked them, you can be able to do so much more with plain JS, but anyways, JQuery is cool too.

AIM

To check whether the value a user inserts in a field is a number or not.

GETTING STARTED

To use JQuery in your web pages, you need to include the library in the <head> part of your document. You can download the JQuery library from https://jquery.org , for the purpose of this tutorial, I am using jquery.js and not the minified version of the library. I actually have no reason for this, but if I'm asked, I'll just say I love to see the finely indented codes inside the jquery.js , call me a fan of Clean Code, lol.

First off, I'll create a simple HTML page template with my jquery library included in the <head> section as you can see in the image below, in the file, I want to have an input field and a button. You can add a bit of styling too, it doesn't hurt.

My input field have the following attributes and values:
'type' : 'text',
'id' : 'myInput',
'placeholder' : 'Enter a value'

The button also have some properties:
'type' : 'button',
'id' : 'check'

Now, just below the input field and the button, I placed a paragraph tag there meant to hold the output from our test (it will state whether or not the value you entered is a number or not). This will not contain any text by default, but I will give it an id property with value 'output' which I am going to manipulate using JQuery.


Save your file on your Desktop, with an HTML extension and then run in your local server and see what you have.



Hope you got a good hang of that? Look forward to more tutorials and walkthroughs.
If you have any question regarding this tutorial, feel free to use the comment box. I'll respond ASAP.

No comments:

Post a Comment

We value your comments, drop one