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.
This is how you should do it.
<input type="text" value="name" onfocus="this.value = this.value=='name'?'':this.value;" onblur="this.value = this.value==''?'name':this.value;">
If they click on it and click off the default value will go back. If they click on it and type something in, it won't try to erase what they put if they go back to click on it again.
A much easier way could possibly be:
placeholder="Name"
Set the 'default' value to "Name". Then, using javascript and the 'onfocus' event, clear the field.
So you would have:
<input type="textbox" value="Name" onfocus="if (this.value=='Name') this.value='';"/>
Basic javascript:
<input type="text" value="name" onfocus='if(this.value=="name"){this.value="";}' />