Clean Code is Good Code
Take a look at the code below, search.htm. It's probably something you've seen before, an HTML search form, and a simple script to clear the contents of a search input the first time the user clicks in it.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"" />
<script type="text/JavaScript">
//set search box to nothing on first focus.
var set="false;"
function clearbox(box){
if(!set){
box.value='';
set="true;"
}
}
</script>
<title>Search Form</title>
</head>
<body>
<form name="form1" id="form1" method="post" action="">
<input name="search" type="text" id="search" onfocus="clearbox(this);" value="Your Search"/>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
When the user clicks in the textbox it gains “focus”. This triggers an onfocus event, for which a JavaScript function call has been provided in the XHTML using:
onfocus="clearbox(this);"
The function has a parameter of this sent to the function, so it knows that it is the search input we will be clearing.
The function is defined in the top of the document inside a <script> tag. When the function is called, if the value of the variable set is equal to false, it clears the searchbox of its default value. We it then sets the variable to true so that the same doesn't happen the next time the user clicks on the search box.