Skip to main content

Clear Default Text using JAVASCRIPT

Many web designers like to add some default text to form inputs like text boxes, to signify what the user should type into the box. When the user clicks the input, this default is removed so they can begin typing. This can be a nice usability improvement when used correctly. Below you’ll find a nice, clean way to approach it, that requires minimal work on your part to get it working.

The HTML

On this page we’re going to work through an example of a single text box that comes with some default text. When the user clicks on the box, the default text is wiped away so that they can begin typing. If they click away from the box, without typing anything in, we will add the default text back so that they don’t forget what was meant to be typed. Check it out below:
Creating this text box is easy, we simply add the default text through the input’s valueattribute, like so:
Enter a date: <input type="text" name="date" value="yy-mm-dd">
This default — known as a “representative value” — suggests that in this case our form is expecting a date in the format “yy-mm-dd” (two numbers for the year, two for the month, and two for the day; for example “05-11-22”). This is very useful for users, since they will all have different preferences for how to enter dates. Coding all of these possibilities into your form-processing code can be a nightmare, so this way you can guide your users to enter the date in the preferred format, and save yourself the trouble.

The JavaScript

The magic part in all of this is accomplished through a sprinkle of JavaScript. You should have some knowledge of event handlers and working with forms to understand what happens next. This script is going to be made » unobtrusive, meaning you can add the JavaScript file to any page and it will just work without having to make big changes to the HTML of the page.
The setup of our JavaScript is as so:
  1. When the page loads, we will save the value of the input as a property of the element, so we can use it later.
  2. When the user clicks (or otherwise focuses) on the element, we check if the current value is the same as this saved default text. If it is, we clear the input. Otherwise we leave it as it is.
  3. When the user clicks away from the element, we check if they’ve filled anything into the text box. If they have, we do nothing. If they’ve left it blank, we’ll fill back in the default text.
This nicely breaks down into three JavaScript functions. First of all, we’re going to need myutil-functions.js file, which provides a slew of general-use functions. (Internet Explorer users, open the .js files with Notepad.) Import that file and this new clear-default-text.jsfile and you’re good to go. Save those two files among your other website files, and add this to the <head> of any pages you need it in:
<script type="text/javascript" src="util-functions.js"></script>
<script type="text/javascript" src="clear-default-text.js"></script>
Finally, and very importantly, for any text inputs that you want this to work on, you need to give them a special class, like this:
<input type="text" name="date" value="yy-mm-dd" class="cleardefault">
Our script checks for the existance of this class in order to work its magic. Those who want to understand how the code works can read on for the full explanation...

Explaining the JavaScript

So, our first function runs when the page loads, and finds all the input elements on the page. If the input has the type “text” (i.e. it’s a one-line text input), and it has the class “cleardefault,” we add event handlers for the focus and blur events.
addEvent(window, 'load', init, false);

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && theInput.className.match(/\bcleardefault\b/)) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
Then we save the input’s current value into a new property that we’re creating, calleddefaultText. This makes use of JavaScript’s handy ability to add arbitrary properties to any element. We simply make up a new one so we can store this information as part of the element.
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}
So, now our inputs are set up, we need the function that run when the focus and blur events occur. They’re pretty simple. First, in both, we have to find the target element that actually fired the event. Once we have this, we check to see if the user has interacted with this input before, and react accordingly.
function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}
And that’s all there is to it. This script can be dropped into any page, and as long as the inputs on the page have been given the right class, it’ll work. Enjoy.

Comments

Popular posts from this blog

Access 2007 and VBA Tutorial

  MS ACCESS 2007:   VBA ENVIRONMENT INTRODUCTION This MSAccess tutorial explains the VBA environment in Access 2007 (with screenshots and step-by-step instructions). See solution in other versions   of MSAccess : Access   2010   Access   2007   Access   2003 WHAT IS VBA? This is what the VBA environment looks like in Microsoft Access 2007: VBA   standards for   Visual Basic for Applications   and is the language embedded within your database in Access 2007. You use   VBA   whenever you do one of the following: Create a new function. Create a new subroutine. Define a global variable. Place code behind an event procedure such as the "On Click" event of a command button. Execute the RunCode action in a macro. These are just some of the examples of when you might be running VBA code. MS ACCESS 2007:   OPEN VBA ENVIRONMENT This MSAccess tutorial explains how to open the VBA environmen...

How to Fix Temporary Profile in Windows 7

Sometimes Windows 7 Operating System fails to read the correct user profile properly, and instead, loads with a temporary profile. If you are keen you will see the following message: "You have been logged on with Temporary profile" This is how you fix the temporary profile problem on Windows 7: A.  Before do anything,  restart the computer 2 or 3 times  to see whether it’s going back to your old correct profile. If this doesn’t work, go to the next step. B.  Rename the temp profile registry and revert back the old registry settings for the correct profile. This methods works especially if the profile is not completely corrupt,. 1. Log in with temp profile. 2. Start registry editor by typing  regedit   in find box of Windows 7. 3. Navigate the following location. 1. Log in with your temporary profile if your account has administrative rights or with the local administrator account. 2. Start the registry editor by typing  regedit ...

Ant - Setup

Apache Ant Ant is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative. The latest Apache Ant version, including its full-source code, class files, and documentation can be found at  http://ant.apache.org. Installing Apache Ant It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions  here . Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed. Download the binaries from  http://ant.apache.org Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools. Create a new environment variable called  ANT_HOME  that points to the Ant installation folder, in this case  c:\apache-ant-1.9.5-bin folder. Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the...