JavaScript: Default Values in Input Elements
Sep 13th, 2009
Style and JavaScript Code
<style>
.input {color:#000000;}
.inputDefault{color:gray}
</style>
<script>
function Default_Text(ele)
{
// element.defaultValue holds default Text
if(ele.value == ele.defaultValue)
{
ele.value = ''; // change default value
ele.className = 'input';
}
else if (ele.value == '')
{
// Input box empty, show default text again
ele.value = ele.defaultValue;
ele.className = 'inputDefault';
}
}
// Loop through form elements and check if it is text, then maintain the
// color values for defaultText depending on the text-box value
function elements()
{
frm = document.getElementById('frm1').elements;
for (ele=0; ele<frm.length;ele++)
{
if(frm[ele].type != 'text') continue;
if (frm[ele].value != frm[ele].defaultValue)
{
frm[ele].className = 'input';
}
else if (frm[ele].value == frm[ele].defaultValue)
{
frm[ele].className = 'inputDefault';
}
}
}
window.onload = elements;
</script>
HTML Code
<FORM id="frm1" METHOD=POST ACTION="">
<!-- Onclick can also be used. But when the text box will receive focus using tab then field value will not cleared. So,onFocus is right here.-->
<INPUT TYPE="text" NAME="txt1" id="tex1" onfocus="Default_Text(this)" onblur="Default_Text(this)" value="Address"> <br/>
<INPUT TYPE="text" NAME="txt2" onfocus="Default_Text(this)" onblur="Default_Text(this)" > <br/>
<INPUT TYPE="text" NAME="txt3" onfocus="Default_Text(this)" onblur="Default_Text(this)" > <br/>
<input type="checkbox" name="chk1">
<INPUT TYPE="submit"> <br/>
</FORM>
The script will clear itself or say- hide default text as soon as input element receive focus.
If input-box is empty after focus lost (on blur) then it will restores the default Value of the
input-box.
Possibly Related posts:
Sometimes you will see a tool-tip for each input-box or you see a default text is already entered in box to understand what should go inside the input box. This script is to provide a way to have default value in each input box in a form, which will clear default text itself when input-box receives focus.