Javascript input box


<form id="commentform" method="post" action="post.php">
    <input type="text" aria-required="true" tabindex="1" size="22" value="vistor" 
       id="author" name="author">
</form>

I set default value “visitor” to the input box. When focus is in text box or mouse enters it, I want to hide “visitor” string and want to show it when it loses focus or mose moves out. how to write the javascript code. thank you.

The web browser stores the starting value as a defaultValue property on the element, so we can make good use of that.

Attach an onfocus and onblur event on to the author field within the form.


var form = document.getElementById('commentform');
form.elements.author.onfocus = hideDefaultValue;
form.elements.author.onblur = showDefaultValue;

On focus, the hideDefaultValue function removes the default value. If you’ve changed the field to something else, then the value that’s there remains there.


function hideDefaultValue {
    if (this.value === this.defaultValue) {
        this.value = '';
    }
}

On blur, the showDefaultValue functions checks to see if the form field is empty. If it is, it puts the default value there instead.


function showDefaultValue {
    if (this.value === '') {
        this.value = this.defaultValue;
    }
}

You can also set and clear a className value on the field. That can be useful if you want the displayed default value to be shown in a different color such as light grey.

how to set the default value to be shown in a different color? thank you.
2,what’t this line meaning? form.elements.author.onfocus

You would have a CSS declaration to specify the color:


.default {
    color: gray;
}

Then as a part of the hideDefaultValue and showDefaultValue, you would set or remove that “default” class name on the form field.

When you click on a field and the default value is hidden, the color should go from grey color back to its normal black color for normal text, so we remove the CSS class name on the field.


function hideDefaultValue {
    if (this.value === this.defaultValue) {
        this.value = '';
        [color="green"]this.className = '';[/color]
    }
}

When we show the default value, we set the CSS class name so that the appropriate CSS declaration can affect that field.


function showDefaultValue {
    if (this.value === '') {
        this.value = this.defaultValue;
        [color="green"]this.className = 'default';[/color]
    }
}

“form” is the that variable contains a reference to the form.
“elements” allows is to access the input fields of the form
“author” is the name of the form field we wish to access
“onfocus” is the event that triggers when click on field and can type in it