Wednesday 27th February 2008Input text value change on click w/wo jQuery
This tutorial is featured on derekharvey.co.uk, the method has been applied to the username and password field.
The reason i created this javascript was because usually when you have a text field and specify a default value when you click on the field the default value needs to be removed in order to fill in your personal details however by adding the remove javascript if the user didn't log in the the value of the field would remain blank so i discovered the attribute defaultValue and this is what i have created for this pretty cool (but basic) effect.
<script>
function clearText(theField)
{
if (theField.defaultValue == theField.value)
theField.value = '';
}function addText(theField)
{
if (theField.value == '')
theField.value = theField .defaultValue;
}
</script><input type="text" name="username" onblur="addText(this);" onfocus="clearText(this)" value="username" />
So let's break it down into little bits and let's start with the clearText function.
function clearText(theField)
{
if (theField.defaultValue == theField.value)
theField.value = '';
}
As you can see about the first argument in the function is 223224theField224 and this is basically the current field we apply this to. Then as you can see from the first if statement in the function we check to see if the default value is the same as the current value and if it is then we set the value to blank. This is so what when the user clicks on the field it doesn't remove the information they may have entered already.
Next we have the addText function.
function addText(theField)
{
if (theField.value == '')
theField.value = theField .defaultValue;
}
As you can see from above the principle behind the function is pretty similar to the clearText function, we have the first argument in the function as theField and all we are doing this time is checking to see if the value of the field is empty and if it is then we set the value to the default field, so this function will be applied as the user moves away from the text field.
So now we have our functions we need out text field, the text field will have two new attributes; one for onBlur and another for onFocus, as shown below
<input type="text" name="username" onblur="addText(this);" onfocus="clearText(this)" value="username" />
Well that's it for this tutorial, i hope this has helped you a little with your javascript.
Alternitavly, if you prefer to use jQuery, here is the code .....
$(document).ready(function() {
$('.rmv-dft-val').click(
function() {
if (this.value == this.defaultValue) {
this.value = '';
}
}
);
$('.rmv-dft-val').blur(
function() {
if (this.value == '') {
this.value = this.defaultValue;
}
}
);
});
Then the HTML will look like this ...
<input type="text" class="rmv-dft-val" name="username" value="username" />
The jQuery framework can be downloaded from http://jquery.com/
Enjoy ...
Leave a Reply