Unobtrusive JavaScript: automatically clear and restore multiple form inputs in focus

Keywords: Javascript IE

Step 1: prepare the form

Prepare your form first, because you want it to run without JavaScript. For example, you might have a comment table that looks like this:

<form>
    <fieldset>
        <label for="author">Name</label>
        <input type="text" name="author" id="author" value="Name" />

        <label for="email">Email</label>
        <input type="text" name="email" id="email" value="Email" />

        <label for="website">Website</label>
        <input type="text" name="url" id="url" value="Website" />

        <label for="comment">Comment</label>
        <textarea id="comment" name="comment"></textarea>

        <input id="submit" name="submit" type="submit" value="Submit" />
    </fieldset>
</form>

Make sure that the type value of each form input is text. This is all we need to do to prepare the form. To summarize the first step, any form input with at least the following properties can be used with the auto clear / restore script:

    <input type="text" value="Name" />
    <input type="text" value="Email" />
    <input type="text" value="Site" />

Step 2: add JavaScript

In a file called "autoclear.js" (or other), add the following JavaScript snippet:

function init(){
        var inp = document.getElementsByTagName('input');
        for(var i = 0; i < inp.length; i++) {
            if(inp[i].type == 'text') {
                inp[i].setAttribute('rel',inp[i].defaultValue)
                inp[i].onfocus = function() {
                    if(this.value == this.getAttribute('rel')) {
                        this.value = '';
                    } else {
                        return false;
                    }
                }
                inp[i].onblur = function() {
                    if(this.value == '') {
                        this.value = this.getAttribute('rel');
                    } else {
                        return false;
                    }
                }
                inp[i].ondblclick = function() {
                    this.value = this.getAttribute('rel')
                }
            }
        }
    }
    if(document.childNodes) {
        window.onload = init
    }

Then call it from your code.

<script src="autoclear.js" type="text/javascript"></script>

Alternatively, the script can be placed in the section of the (X) HTML document that contains the form head. In addition, to improve performance, you may want to use an online JavaScript compressor to compress scripts.

When everything is ready, upload it and check it out. Everything should be good, even in IE 6! ()

Effect: the value entered after submission will be cleared!

Posted by blackswan on Tue, 31 Dec 2019 21:43:39 -0800