jQuery to add textfield labels

Posted on Friday, December 25th, 2009 at 12:00 pm

In the world of web aesthetics a nice principle to follow is the less clutter the better. Traditional forms have contained a label and then a text input usually. More and more we’re beginning to see the labels being placed inside the text field until the user selects them, at which point they can type whatever. The reason we may be seeing it more often is because jQuery, as usual makes what is otherwise a fairly time-consuming task and makes it simple.  To get an idea of what I’m talking about you can see a demo here.  I checked the demo.  I’m pretty sure that the tooltips work fine in Firefox, but are incorrectly positioned in Safari, and I don’t even want to know for IE.  I’m sure this is no fault of the plugin, but that there is just some conflict in the plugin CSS and my demo template CSS.  I just really didn’t feel like figuring it out.  On top of all that, if you don’t have Firefox to view the demo with shame on you

Let’s think about what it is we are wanting to accomplish.  Generally we want a form with no labels.  Instead our labels are a prefilled value inside the form field.  However, when a field with one of these prefilled labels is clicked or tabbed to we want to empty the field and ready it for typing.  Next if new data is entered the data should stay in the field, and if no data is entered the field should return to the prefilled label.  Lastly, if the user focuses a field that they have already entered data into we want to make sure that we don’t empty the field, but instead just select the entered data and ready it for editing.  One last thing.  Because our field label disappears when the field is selected I felt that it made sense to make sure that the user doesn’t forget what they are typing into the field.  To accomplish this I used the jQuery Tools tooltip plugin.  I won’t explain this too much, but for this demo I pretty much just copied and pasted their demo code from their site.  Nonetheless, this is a really powerful and flexible plugin, and on top of everything really looks great.

On to the code.  First we’ll take a look at the HTML.

The HTML

<!-- div that will show our tooltip -->
<div id="mytooltip">&nbsp;</div>

<!-- form with labels in the field label in the 'id' and tooltip in the 'title' -->
<form name="myForm" id="myFormId" method="post" action="#">
    <input type="text" name="firstname" id="Your First Name" value="" title="Enter Your First Name" /><br /><br />
    <input type="text" name="lastname" id="Your Last Name" value="" title="Enter Your Last Name" /><br /><br />
    <input type="text" name="mycolor" id="Your Favorite Color" value="" title="Enter Your Favorite Color" /><br /><br />
    <input type="text" name="mycat" id="Your Favorite Cat" value="" title="Enter Your Favorite Cat" /><br /><br />
    <input type="submit" name="mySubmit" />
</form>

Two things here.  First is an empty div that we'll use as our tooltip.  Next I'll post the CSS that we use to style the tooltip.  Next is our form.  Notice that we don't have any labels.  Instead we just have four input fields and a submit button.  Inside each of the text fields we have an id and a title.  The id is the label value we want to be input into our text field if no user text has been input.  The title is the copy we want to show up in our tool tip when the user focuses that form field.  Entering the tooltip into the title attribute is part of the tooltip plugin I'm using.  Otherwise, that's about it for the HTML.

Now let's take a look at the CSS.

The CSS

<!-- style our tooltip -->
<style rel="stylesheet" type="text/css">
	#mytooltip {
	    background-color:#000;
	    border:1px solid #fff;
	    padding:10px 15px;
	    width:100px;
	    display:none;
	    color:#fff;
	    text-align:left;
	    font-size:15px;

	    -moz-box-shadow:0 0 10px #000;
	    -webkit-box-shadow:0 0 10px #000;
	}
</style>

This just styles our tooltip, which again I just copied from the jquery Tools tooltip plugin docs. Now time to make everything work.

The jQuery

<!-- connect to the tool that will allow the tooltips plugin to work.  the jquery library is included here. -->
<script src="http://cdn.jquerytools.org/1.1.2/jquery.tools.min.js"></script>

<script type="text/javascript">
	$(document).ready(function()
	{
		//runs anytime one of the form fields focuses
		$("#myFormId :text").focus(function()
		{
			//run the setvalues method to make sure our label values for each text box is correct
			setvalues();

			//get the actual label value of our text field.  This is the input 'id'.
			var textfieldvalue = $(this).attr("id");

			//get the current value of the text field
			var initialvalue = $(this).val();

			//if the initial value of the text field is equal to the label value of the text field
			//then we know that the user has not entered any data and can therefore be emptied and
			//prepared for typing
			if(initialvalue == textfieldvalue)
			{
				//set the value to nothing
				$(this).val("");
			}
			else
			{
				//if the user has entered data already make sure that the value is selected so the
				//user does not have to backspace or double-click.  Keep the form keyboard based.
				$(this).select();
			}
		});

		//run tooltip code
		showtooltips();

		//run focus field method so the first field is initially focused
		focusField();
	});

	/* **********  SET VALUES  ********** */
	setvalues = function()
	{
		//for each text field in our form let's check the value and set the field equal to its
		//label if necessary.
		$("#myFormId :text").each(function()
		{
			//get the actual label value of our text field.  This is the input 'id'.
			var textfieldvalue = $(this).attr("id");

			//get the current value of the text field
			var initialvalue = $(this).val();

			//if it is equal to nothing set the field equal to its label value
			if(initialvalue == "")
			{
				$(this).val(textfieldvalue);
			}
		});
	}

	/* **********  FOCUS FIELD  ********** */
	focusField = function()
	{
		//set the focus initially to the first name field
		$("input[name='firstname']").focus();
	}

	/* **********  SHOW TOOLTIPS  ********** */
	showtooltips = function()
	{
		//show the tooltip for any field in our form.  Only shows on focus by default. Pretty cool!!
		$("#myFormId :input").tooltip(
		{
			//set tooltip properties
			position	:	"bottom center",
			tip		:       "#mytooltip",
			effect		:	"fade",
			opacity		:	"0.7",
			offset		:	[15, 0]
		});
	}
</script>

So, first off we need to get the jQuery library and Tooltip plugin.  The jQuery Tools site that offers the tooltip plugin offers their plugin code via the Content Delivery Network.  They also include the jQuery library in this.  So first off we just set a source to the cdn url to get the jQuery library and plugin.  If you choose not to use this, you can download the actual tooltip plugin at the jQuery Tools website and of course you will then need to include the jQuery library.

Once we have our library and plugin we can start writing the javascript.  We're doing three things here to get this to work.  First we are setting up a listener for each time one of our text input fields is focused.  When this happens we check the focused field to determine if any user input already exists.  If not we empty the field, and if so we just select what the user had previously entered.  Second, when the page initially loads we run a function called 'focusField'.  This function just moves the focus to a certain field in our form.  In this case it's the first name field.  Thirdly, we run a function called 'showtooltips' that does none other than 'show tool tips'.  This code is again pretty much just copied straight from the docs.  And again, if you would like to know more check out the docs for the plugin.

Lastly, we have the all important 'setvalues' function that manages all of our labels each time one of our text fields is focused.  This function takes advantage of the super cool jQuery each() method.  We all know that one of the greatest things about jQuery is its ability to select large amounts of similar data in the DOM (like our input text fields).  But by simply adding the each() method after our selector we can specify a function to run on each element that jquery selects.   Maybe not a big deal for our small form, but to be able to loop through all the form fields and perform some action on each with just a few lines of code is pretty cool in my book.

Anyways, we select our input fields in our form, run the each() method on them that runs a function that checks to see if the user has entered any data.  If so it leaves it alone, and if not it sets the value back to the label stored in the fields 'id'.  To accomplish this we set two vars that hold the initial value before a field was focused, and text field value that holds the label for the text field stored in the 'id'.

The good news is that once you have this code in place you can continue to add text inputs and they will pick up the label value you add in the 'id' and the tooltip you add in the 'title'.

My personal opinion of this type of form tool is a little bit mixed.  I like the idea of being concise with form elements and not cluttering up the screen with a bunch of labels.  But being concise should never be used at the expense of clarity.  Clarity is a necessity with web applications, conciseness is a luxury.  I've kind of solved the issue of the disappearing label by using tooltips, but what happens if you are getting a telephone number that is broken into three fields.  And also remember that using this type of label introduces new form validation obstacles.  For example now you have to check for the prefilled value and treat it as an empty value.  And also remember that because you should never rely solely on javascript validation you will also have to set up new validation using whatever server-side language you're using.  All this aside, I do think using form labels like this is pretty cool, but I'll probably just use it for smaller forms like a login or join email list form.  But hey, go crazy!

Tags
CategoryJavascript

Leave a Reply

*
(Won't be published) *