1. Computing & Technology

JavaScript By Example

DOM Form: 4. Changing Values in Forms

From , former About.com Guide

While form fields have lots of extra attributes that other elements in a web page do not have, there is nothing special about how you get and set those attributes. Updating the value within an input field using JavaScript is done in exactly the same way you would change the src of an image or the class of a row of a table.

In this example we have a default email address that displays in the email input field when the page first displays and have JavaScript remove that from the field when the field first gets the focus. Any subsequent occassions when the field gets the focus where the field contains a different value will not update the value.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example F04</title>
</head>
<body>
<form action="#">
<div>
<label for="email">Email: l</label>
<input type="input" id="email" name="email" value="someone@example.com" /><br>
<input type="submit" value="Submit" />
</div>
</form>
<script type="text/javascript" src="exampleF04.js"></script>
</body>
</html>

JavaScript


if (window.addEventListener)
addEvent = function(ob, type, fn ) {
ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
var eProp = type + fn;
ob['e'+eProp] = fn;
ob[eProp] = function(){ob['e'+eProp]( window.event );};
ob.attachEvent( 'on'+type, o[eProp]);
};
 
clearEmail = function() {
var E = document.getElementById('email');
if ('someone@example.com' === E.value) E.value = '';
}
 
addEvent(document.getElementById('email'),
'focus',
clearEmail);

©2012 About.com. All rights reserved.

A part of The New York Times Company.