JavaScript: Default Values in Input Elements

This script provides input help to users going to fill a form on your website.
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.
Style and JavaScript Code

    .input {color:#000000;}
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;

  <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/>

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

  • # 1 - by Samoys

    lot about you

  • # 2 - by Samoys

    lot about you

  • # 3 - by BAMO

    excellent code, if there was something similar for 'selections' too…

  • # 4 - by BAMO

    excellent code, if there was something similar for 'selections' too…

Comments are open for an year period. Please, write here on Facebook page.