Home / jQuery: Changing the default text value on focus, and showing plain text in a password field Part 1

jQuery: Changing the default text value on focus, and showing plain text in a password field Part 1

Last year I posted a couple of jQuery articles about how to change the default text value on focus and show plain text in a password field and then make it a regular password field on focus, with examples in the pages about how to do it. I did not post a full standalone working example which someone requested a couple of days ago, so follow those posts up here with a full standalone example.

Full example

The full example is as follows below. This full working example can be found by clicking here along with the same source code illustrated below.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
<head>
 
<script language="javascript" src="/js/jquery-1.3.2.min.js"></script>
 
<script language="Javascript">
 
$(document).ready(function() {
 
	$('#password-clear').show();
	$('#password-password').hide();
 
	$('#password-clear').focus(function() {
		$('#password-clear').hide();
		$('#password-password').show();
		$('#password-password').focus();
	});
	$('#password-password').blur(function() {
		if($('#password-password').val() == '') {
			$('#password-clear').show();
			$('#password-password').hide();
		}
	});
 
	$('.default-value').each(function() {
		var default_value = this.value;
		$(this).focus(function() {
			if(this.value == default_value) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = default_value;
			}
		});
	});
 
});
 
</script>
 
<style type="text/css">
 
#password-clear {
    display: none;
}
 
</style>
 
</head>
<body>
 
<form>
<div>
    <input class="default-value" type="text" name="email" value="Email Address" />
</div>
<div>
    <input id="password-clear" type="text" value="Password" autocomplete="off" />
    <input id="password-password" type="password" name="password" value="" autocomplete="off" />
</div>
</form>
 
</body>
</html>

Doing it without modifying the HTML form

There may be circumstances when you can add Javascript/jQuery to the page but not modify the HTML template so everything needs to be done in Javascript. I show how to do this in part 2 of this post.

Toggling a password field by changing the input type

It’s possible with regular Javascript to change an input’s type but it doesn’t work in IE versions less than 9, and jQuery prevents you from being able to do it for this reason. Read my follow up post "toggling a password field between plain text and password" for more information.