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 a util-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.js file 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;
    }
}

Remember to add the addEvent function, which simply adds event listener to a given HTML element

function addEvent(element, event, handlerFunc, useCapture) {
  element.addEventListener(event, handlerFunc, useCapture);
}

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

Ant vs. Maven vs. Gradle: Which Java Build Tool Should You Use in 2026?

If you're working on a Java project, at some point you'll need a build tool - something that compiles your code, manages dependencies, runs tests, and packages everything into a deployable artifact. Three names come up again and again in that conversation: Apache Ant , Apache Maven , and Gradle . Each represents a different era and a different philosophy of how a build process should work, and understanding that history makes it much easier to pick the right one for your project today. The Short Version Ant gives you complete, low-level control over every step of your build, at the cost of writing (and maintaining) a lot of that logic yourself. Maven trades flexibility for standardization - it makes strong assumptions about how your project is structured, and in exchange, handles most of the build and dependency work for you with minimal configuration. Gradle was built to take the best of both: Ant's flexibility and Maven's conventions and dependency management,...

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: 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. 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. Log in with your temporary profile if your account has administrative rights or with the local administrator account. Start the registry editor by typing  regedit   in find box of Windows 7. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\Cu...

Top 10 Alternatives to Internet Download Manager (IDM) in 2026

Internet Download Manager (IDM) has long been one of the most popular tools for speeding up downloads, resuming interrupted transfers, and organizing files pulled from the web. But it's Windows-only, it's paid software, and its browser-extension integration doesn't always keep pace with frequent Chrome, Edge, and Firefox updates. If you're looking for an alternative — whether for cost, platform compatibility, or just a cleaner experience — here are ten solid options actively maintained and worth using in 2026. A quick note before the list: always download these tools from their official websites or verified app stores. Older or lesser-known download managers have a history of bundling unwanted browser extensions or adware in their installers, so it pays to be careful about the source. 1. Free Download Manager (FDM) FDM is probably the closest one-to-one swap for IDM available today. It supports multi-segment accelerated downloads, integrates with your browser via ext...