I am making a simple form with about eight input fields. I want the initial value in the field to indicate what people are supposed to enter. For example value=\"name\" so that
Just for S&G's I thought I would post a reusable jQuery solution for this problem.
var formDefaulter=function(){
//Class to hold each form element
var FormElement=function(element){
var that=this;
this.element=element;
var initialVal=this.element.val();
var isEdited=false;
this.element.focus(function(){clearBox()});
this.element.blur(function(){fillBox()});
var clearBox=function(){
if(!isEdited){
that.element.val("");
isEdited=true;
}
}
var fillBox=function(){
if(that.element.val()==""){
that.element.val(initialVal);
isEdited=false;
}
}
}
var add=function(elementId){
new FormElement($('#'+elementId));
}
return{
add:add
}
}();
Then you just have to attach each element using an ID attribute value. Like so:
$(function(){
formDefaulter.add('contact_name');
formDefaulter.add('contact_email');
formDefaulter.add('contact_msg');
});
This also refills the form element with its original value if its content is deleted. Anyway, hopefully this is helpful to someone.