Form.inputHint()

Snippets are small pieces of code that do not fit in the UvumiTools plugin category. Please note that each of these semi-useful functions requires Mootools 1.2.

Allows you to display default text like "Type your name" in an input field when it has no pre-defined value. Accepts one parameter: the default phrase to display. If no parameter is passed, it will use the input's current value (only recommended when you know the form will always be loaded with no existing content).

You can apply this function to each input individually (better if the inputs may contain existing content and you want to pass a different default value to each input), or to a form element, which will patch each text input and textarea it contains (good if all the inputs are loaded with default values).

Element.implement({
inputHint : function(val){
switch(this.get('tag')){
case 'form':
this.getElements('input[type="text"],textarea').inputHint(val);
return this;
case 'input':
case 'textarea':
this.store('default',(val||this.get('value')));
this.addEvents({
'focus':function(){
if(this.get('value') == this.retrieve('default')){
this.set('value', '');
}
},
'blur':function(){
if(this.get('value').clean() == ''){
this.set('value', this.retrieve('default'));
}
}
}).fireEvent('blur');
default: return this;
}
}
});

Usage:

$('myInput').inputHint("Type your email address");       //display the passed text inside the input if it's empty.
$('myForm').inputHint();  //Goes through each text input and textarea and uses the existing value as default.
//Use this one carefully, only if the form may not contain any other value when page is loaded

Demo:

Click on the input like you are going to type something in. The input clears itself. Then click outside without typing anything and it will restore the default value.