View Demo

Creating a login (or any form for that matter) can be trickier than it looks. After all how difficult can two text boxes a button and some labels be? There are different ways to accomplish this task, some using more proper semantically correct markup techniques than others. This example will attempt to give a real world case of how easy it can be to target elements contained inside the form with minimal scripting using the jQuery framework.

We’ll first start out with some html markup, notice the lack of css class attributes or JavaScript event handlers present.

<fieldset>
	<legend>Log In</legend>
	<p id="loginResult">Invalid login.. try again.</p>
	<form id="login" method="post">
		<dl>
			<dt><label for="username">Username:</label></dt>
			<dd><input id="username" type="text" /></dd>
			<dt><label for="password">Password:</label></dt>
			<dd><input id="password" type="text" /></dd>
		</dl>
		<p><input type="submit" value="Login" /></p>
	</form>
	<small>u:username / p:password</small>
</fieldset>

The next step we take is to target each element down the list and assign it a css class. We do this by using jQuery’s element specific selectors :text and :submit.

	$(function(){
		$('form#login :text').addClass('inputTextbox');
		$('form#login :submit').addClass('inputSubmitBtn');
	});

Next, we’ll add the event handler for the submit button by using .click(). To make things easier on ourselves we could always shorten our code by chaining the click event at the end of our submit button selector which was already defined in the previous step.

$('form#login :submit').addClass('inputSubmitBtn').click(function() {
     // click event code
}

Throw in an animation for good measure to display a message for invalid attempts and you’re good to go. Here is the full JavaScript code we’re working with.

		$(function(){
			$('form#login :text').addClass('inputTextbox');
			$('form#login :submit').addClass('inputSubmitBtn').click(function(){
				if($('#username').val() != "username" || $('#password').val() != "password")
				{
					for(i=0;i<5;i++)
						$("#loginResult").animate({opacity: 'toggle'}, 500 );	
						
					$("#loginResult").fadeIn(500);					
					return false;
				};
			});
	    });
More