October 14, 200917 yr Clearing the value of a form field I'm not entirely sure why, but I hate online forms that require me to clear the default value before I can add my own, especially on an online store. Default values can be useful and I always think that a form with self-clearing elements looks more polished and professional than a form where I have to strip out the default value first. If this is simply a problem of not knowing a good solution, I would like to show just how simple it can be. The basic idea is to create a form element with a value that clears when the form is selected. By far the easiest way of doing this is to give the form field an onclick event. Something like: <input type="text" name="username" value="username" onclick="if(this.value=='username'){this.value='';}" /> There are three problems with this example. Our first problem is that people may click the label instead of the form element and users without a mouse won't click anything. I often find that it's easier to move from one form element to the next by using the tab button -- especially if I'm using my laptop. Coming across a field using these methods will select the word 'username'; clicking is required to clear the value. Using the focus event solves this problem. <input type="text" name="username" value="username" onfocus="if(this.value=='username'){this.value='';}" /> Now the value will clear even when tabbing to the form field. By using the sister event, blur, the value can be replaced when the user moves away from the form field <input type="text" name="username" value="username" onfocus="if(this.value=='username'){this.value='';}" onblur="if(this.value==''){this.value='username';}" /> The second problem comes when you, the coder, have to assign this functionality to all fields in a large form. The inline scripts would have to be adjusted each time. Inputs have an attribute that can be accessed by JavaScript to aid this: defaultValue. The form field could now looks like this: <input type="text" name="username" value="username" onfocus="if(this.value==this.defaultValue){this.value='';}" onblur="if(this.value==''){this.value=this.defaultValue;}" /> If you ever need to do the job quickly, the combination of the focus and blur events in the code above will work every time. However, if you're a responsible JavaScript coder and believe in unobtrusive JavaScript, keeping scripts away from markup, or even just stream-lining HTML, you'll have spotted the third problem in the original piece of code: inline styles are something to be avoided. Since all the form fields have the same script attached, a simple JavaScript function is all that will be needed. In its most basic form, the script needs to assign focus and blur event handlers to all input tags with a default value. window.onload = function() { // Find all inputs on the page var inputs = document.getElementsByTagName('input'); // Loop through each of the elements and assign the handlers for (var i in inputs) { // Only asign the handlers to inputs with a default value if (inputs[i].defaultValue) { // Wrap the function in a closure to ensure that i points to // the correct input tag (function() { // Clear the value on focus inputs[i].onfocus = function() { if (this.value == this.defaultValue) { this.value = ''; } }; // Restore the value on blur inputs[i].onblur = function() { if (this.value == '') { this.value = this.defaultValue; } }; // Automatically execute the function }()); } } }; Although that script will work efficiently, it will be a little harsh. It will replace any event currently assigned to any of the inputs, or the window load. To finalise the script, this needs to be addressed. For extra credit, the script should be expanded to include textareas. The first point can be easily solved with a good addEvent function. There are hundreds of addEvent functions online, from Simon Wilson's simple event closure (1) to Dean Edwards' 50 line complete solution (2). Replace the three event calls with references to your favourite addEvent function and the first point is fixed. Setting the function us to check for textareas can catch out the unprepaired or anyone new at JavaScript. The function getElementsByTagName does not return an array, it returns a NodeList. The two are as similar as English and American; some things are the same, but the differences can be embarrasing. The most important difference that this script needs to worry about is a NodeList does not have a push() method, so it's not possible to add anything to it. This can be circumvented by simply adding all the values from two NodeLists to an array. // Add an event to the window load without overwriting // Don't forget the event argument addEvent(window, 'load', function(e) { // Create an array to store the inputs and textareas var defaulters = [], inputs = document.getElementsByTagName('input'), textareas = document.getElementsByTagName('textarea'); // Loop through the inputs and add them to our array for (var i in inputs) { // Filter out all inputs without a default value if (inputs[i].defaultValue) { // Create a closure to ensure we get the correct input (function() { // Add the reference to the input to our array defaulters.push(inputs[i]); // Automatically execute the closure }()); } } // Repeat the loop for textareas for (var j in textareas) { if (textareas[j].defaultValue) { (function() { defaulters.push(textareas[j]); }()); } } // Loop through our new array and add events for (var k in defaulters) { (function(e) { // Clear the default value on focus addEvent(defaulters[k], 'focus', function(e) { if (this.value == this.defaultValue) { this.value = ''; } }); // Replace the default value on blur addEvent(defaulters[k], 'blur', function(e) { if (this.value == '') { this.value = this.defaultValue; } }); }()); } }); It is possible to expand this script to add a class to any element with a default value so that the default values look different from user-entered values. The script could also include a check for a certain class or attribute to prevent this script removing any information that has been added server-side to help the user. For an example of the final script in this tutorial in action, please visit http://www.sk80.co.uk/form_elements.html This script is offered freely, with no copyright, in the hope that I never have manually clear a form element again.
October 14, 200917 yr Awesome right up, I don't know which bugs me more, when sites require me to clear the field, or it doesn't have the onblur. Too many sites miss the onblur bit, and it feels so half arsed Pretty comprehensive write up, i'm definitely adding this script to my codebank
October 18, 200917 yr Author Thanks for the replies Because I'm bored enough, I've looked around and noticed how to combine the two for...in loops and save an entire 9 lines! // Add an event to the window load without overwriting // Don't forget the event argument addEvent(window, 'load', function(e) { // Create an array to hold the inputs and textareas var defaulters = [], inputs = document.getElementsByTagName('input'), textareas = document.getElementsByTagName('textarea'); // Loop through the inputs and textareas for (var i = 0, il = inputs.length + textareas.length; i < il; i++) { // Create a closure to ensure the correct value of i (function() { // If i is less than the length of inputs, add the next input to // our array, otherwise add the next textarea defaulters.push((i < inputs.length) ? inputs[i] : textareas[i - inputs.length]); // Automatically execute the closure }()); } // Loop through our new array and add events for (var k in defaulters) { (function(e) { // Clear the default value on focus addEvent(defaulters[k], 'focus', function(e) { if (this.value == this.defaultValue) { this.value = ''; } }); // Replace the default value on blur addEvent(defaulters[k], 'blur', function(e) { if (this.value == '') { this.value = this.defaultValue; } }); }()); } });
Create an account or sign in to comment