Search code examples
javascripthtmltextinput

Default text on input


How to set blank default text on input field and clear it when element is active.


Solution

  • In modern browsers, you may set the placeholder attribute on a field to set its default text.

    <input type="text" placeholder="Type some text" id="myField" />
    

    However, in older browsers, you may use JavaScript to capture the focus and blur events:

    var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
        if (elem.addEventListener) elem.addEventListener(type, fn, false);
        else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
    },
    textField = document.getElementById('myField'),
    placeholder = 'Type some text'; // The placeholder text
    
    addEvent(textField, 'focus', function() {
        if (this.value === placeholder) this.value = '';
    });
    addEvent(textField, 'blur', function() {
        if (this.value === '') this.value = placeholder;
    });
    

    Demo: http://jsbin.com/utecu