A better solution, which enables this feature on all inputs that has the class "focusclear", and separates the js from the html nicely.
It also uses the "defaultvalue" of the input, which means you dont need to write what the default value of your input is in the js, just change it normally in the html and the js still works.
Code:
<html>
<head>
<title>On blur</title>
</head>
<body>
<input type="text" class="focusclear" value="Username..." />
<input type="password" class="focusclear" value="Password..." />
<script type="text/javascript">
Array.prototype.inArray = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (!!input[i].className && input[i].className.split(' ').inArray('focusclear')) {
input[i].onfocus = function() {
if (this.value == this.defaultValue) {
this.value = '';
}
};
input[i].onblur = function() {
if (this.value == '') {
this.value = this.defaultValue;
}
};
}
}
</script>
</body>
</html>
Just remember that the js needs to run after the html for the inputs, because otherwise the code cannot find them, do this either by placing the code at the bottom of the page like I did, or enclosing it all in:
Code:
window.onload = function() { ... }
Also, here is a modified version which makes the value in password fields visible if it is the default value, but when you type in your password it changes to stars, and it also changes back to text if you remove focus from the field when it's empty.
Code:
<html>
<head>
<title>On blur</title>
</head>
<body>
<input type="text" class="focusclear" value="Username..." />
<input type="text" class="focusclear password" value="Password..." />
<script type="text/javascript">
Array.prototype.inArray = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (!!input[i].className && input[i].className.split(' ').inArray('focusclear')) {
input[i].onfocus = function() {
if (this.value == this.defaultValue) {
if (this.className.split(' ').inArray('password')) {
this.setAttribute('type', 'password');
}
this.value = '';
}
};
input[i].onblur = function() {
if (this.value == '') {
if (this.className.split(' ').inArray('password')) {
this.setAttribute('type', 'text');
}
this.value = this.defaultValue;
}
};
}
}
</script>
</body>
</html>
As you can see, you now need to set the type on your original field to text, and then give it a class of "password" for this to be enabled.
Hope I helped.