Amiya Sahu Web Developer

Clear input Field on Focus using JQuery

This piece of code will clear the text input field on focus if the field is not changed by the user.

HTML code

<input type="text" id="username" data-default-value="username" value="username">

JQuery code

jQuery(document).ready(function ($) {
    var $field = $('#username'), 
        defaultValue = $field.data('default-value');
    $field.on('focus', function (event) {
        var $this = $(this);
        if ($this.val().trim() === defaultValue) $this.val('');
    });
    $field.on('focusout', function (event) {
        var $this = $(this);
        if ($this.val().trim() === '') $this.val(defaultValue);
    });
});

Here is a live example.