Picnic Website Code Tutorials

Clear The Input Field On Click Tutorial

This simple script will clear a input field when you click inside it. Easy-Peasy-Japaneasy! mooning smiley

Example...

The Small Script

<script type="text/javascript">
function clearDefault(a){if(a.defaultValue==a.value){a.value=""}};
</script>

And on the Input

<input value="Clear Input Field" onFocus="clearDefault(this)">

...Or There's This One

This puts the default text back in (if no text has been input) once you click outside the input field. Note: I changed "clearDefault" to "clearText" in this script/input so it would not affect the script/input above.

Example...

The Small Script

<script type="text/javascript">
function clearText(a){if(a.defaultValue==a.value){a.value=""}else{if(a.value==""){a.value=a.defaultValue}}};
</script>

And on the Input

<input value="Clear Input Field!" onFocus="clearText(this)" onBlur="clearText(this)">

...Even Better Yet!

This script fades the default text in the input field, clears it when it's clicked in, and puts the default text back in (if no text has been input) once you click outside the input field. Just like Google! Note: you must put .faded{color:#aaa;} in the CSS, and the script must go below the input using it. Also, make sure the form id and the corresponding script id match up. In the example below, it's "login". Also, in order to add another input field with faded text, just add this line to the script - setDefaultText(form.elements.username, 'Default Text'); The "username" in that extra line, corresponds to the name attribute in the input. Those must also match up!

Example...

The Slightly Larger Script

<script type="text/javascript">
var form = document.getElementById('login');
setDefaultText(form.elements.username, 'Click in this input field to clear the text!');

function setDefaultText(field, text) {
    text = text || field.defaultText;
    if (field.value === '') {
        field.value = text;
        field.defaultText = text;
        addClass(field, 'faded');
    }
    field.onfocus = function () {
        removeDefaultText(this);
    };
    field.onblur = function () {
        setDefaultText(this);
    };
}
function removeDefaultText(field) {
    if (field.value === field.defaultText) {
        field.value = '';
        removeClass(field, 'faded');
    }
}
function hasDefaultText(field) {
    return (field.value === field.defaultText);
}
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
    if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}
</script>

And on the Form/Input

<form id="login" action=""><input type="text" name="username"></form>

Sponsors

Top Donators

Friends of Mine