Search code examples
jqueryinputdefaultonfocus

How to remove default value of input on focus


I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

<input type="text" name="kp1_description" value="Enter Keypress Description">

Solution

  • $(document).ready(function(){
        var Input = $('input[name=kp1_description]');
        var default_value = Input.val();
    
        Input.focus(function() {
            if(Input.val() == default_value) Input.val("");
        }).blur(function(){
            if(Input.val().length == 0) Input.val(default_value);
        });
    })​
    

    That should do it.

    Updated, Forgot that focus does not have a 2nd parameter for the focus-out event because there is none, it has to be chained with blur:

    http://jsfiddle.net/hDCsZ/

    you should also think about creating your own function for this such as:

    $.fn.ToggleInputValue = function(){
        return $(this).each(function(){
            var Input = $(this);
            var default_value = Input.val();
    
            Input.focus(function() {
               if(Input.val() == default_value) Input.val("");
            }).blur(function(){
                if(Input.val().length == 0) Input.val(default_value);
            });
        });
    }
    

    Then use like so

    $(document).ready(function(){
        $('input').ToggleInputValue();
    })​