Clear default text from input boxes using Javascript

Providing labels is a great way to help users interact with your website properly. I like to put instructional text inside text boxes to save space. Users get annoyed when the text inside the box they click on does not disappear when they are ready to type. Users do not want to backspace default instructional text before typing in boxes, so some code is required to make this happen.

I would like to share two small Javascript functions. The first clears out default text box contents automatically when a user clicks on the box. The second restores the default instructional text if the user leaves the box empty.

Implement these functions using onfocus=”wash(this);” and onblur=”checkWash(this);” on your text input control. You may want to avoid the second function on text fields where input is optional, so the user can leave the text box blank.

function wash( anInput ){
if(anInput.value == anInput.defaultValue) anInput.value = '';
}

function checkWash( anInput ){
if(anInput.value == '') anInput.value = anInput.defaultValue;
}

Try it

Look, I made a demo!


2 comments

  1. Hi, I’m trying to implement your code snippet and I’m not sure where I need to place the code. I’m building a website in wordpress and want the words “username” and “password” disappear in the input login boxes when someone clicks them. Your article sounds like it has the solution – could you tell me where to place the code? Thanks a lot in advance!

  2. Tim,

    You could view the source of this page since I’ve built a demo above. The two functions need to be placed in a script block like this:

    <script type="text/javascript">
    <!--
    function wash( anInput ){
    if(anInput.value == anInput.defaultValue) anInput.value = '';
    }
    function checkWash( anInput ){
    if(anInput.value == '') anInput.value = anInput.defaultValue;
    }
    //-->
    </script>

    Then, create a text box on your page with code like this:

    <input type=”text” id=”userName” value=”User name” onfocus=”wash(this);” onblur=”checkWash(this);”>

    Your password text box should be type=”password” instead of type=”text”

Leave a comment

Your email address will not be published. Required fields are marked *