As we all know jQuery is a JavaScript library. It is a write less and do more type of programming approach. It is simple, easy to learn and write, event driven and AJAX enabled. Using jQuery HTML element accessing and manipulation become very easy. It has many pre-defined function to use. Like hide(), show() etc.
I am creating a demo application to show how it is easy to validate a login form using jQuery. So let’s start VWD and create a new web application project. In default.aspx delete all the content under the second content place holder and write html code to develop a small login form having user name, password, login button and a reset button.
<table cellpadding="4"> <tr> <td> User name </td> <td> <input id="txtUserName" /> <span id="spnUserName" /> </td> </tr> <tr> <td> Password </td> <td> <input id="txtPassword" /> <span id="spnPassword" /> </td> </tr> <tr> <td /> <td> <input id="btnLogin" type="button" value="Login" /> <input type="reset" /> </td> </tr> </table>
Now in the first content place holder first add the jQuery library from the solution explorer. For that you can drag it down or write code by hand. Just under the jQuery library add another script tag to write jQuery code. If you want to write all your jQuery code in external .js file then you have to add it like jQuery library. I am writing all this in the same file because I want to make this example simple.
// Check html loading is done or not. $(document).ready(function () { // When login button is clicked then validate. $('#btnLogin').click(function () { // Validate user name. if ($('#txtUserName').val() == '') { $('#spnUserName').text('User name can not be blank'); return false; } else { $('#spnUserName').text(''); } // Validate password. if ($('#txtPassword').val() == '') { $('#spnPassword').text('Password can not be blank'); return false; } else { $('#spnPassword').text(''); } // Submit the form if there is no validation error. document.forms[0].submit(); }); });
$ is for querying the html of the web page. ready() function is to determine that whether the html loading is done or not. We should start our work after all the elements are ready on the browser. jQuery can handle events. It is having a very readable syntax and naming convention. Like when someone will click on the button then do the validation. Then one by one do all your validations, here I only check the required fields. Every time I am querying the html using the ids of the elements.
$('#txtUserName').val()
That means value of the control who have txtUsernName id. You can find many of the functions from any good jQuery tutorial.
Now execute the application and without giving any user name or password click on the login button, you can see now that the page is not submitting and the validation notifications are showing. Now give a user name and password and again click on the login button and the page submit and all the validation notification are gone.
This is the first step towords the jQuery world.