Background text in input type text

Here is how you can get a placeholder using HTML5:

<input id="textfield" name="textfield" type="text" placeholder="enter something" />

EDIT:

I no longer recommend hacking together your own polyfills as I showed below. You should use Modernizr to first detect whether a polyfill is needed in the first place, and then activate a polyfill library that fits your needs. There is a good selection of placeholder polyfills listed in the Modernizr wiki.

ORIGINAL (contd):

And here is a polyfill for compatibility:

<input id="textfield" name="textfield" type="text" value="enter something" onfocus="if (this.value == 'enter something') {this.value="";}" onblur="if (this.value == '') {this.value="enter something";}">

http://jsfiddle.net/q3V4E/1/

A better shim approach is to run this script on page load, and put your placeholders in the data-placeholder attribute, so your markup looks like this:

<input id="textfield" name="textfield" type="text" data-placeholder="enter something">

and your js looks like this:

var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
    inputs[i].value = inputs[i].getAttribute('data-placeholder');
    inputs[i].addEventListener('focus', function() {
        if (this.value == this.getAttribute('data-placeholder')) {
            this.value="";
        }
    });
    inputs[i].addEventListener('blur', function() {
        if (this.value == '') {
            this.value = this.getAttribute('data-placeholder');
        }
    });
}

http://jsfiddle.net/q3V4E/4/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)