Delete default value of an input text on click

前端 未结 13 1973
逝去的感伤
逝去的感伤 2020-11-29 18:24

I have an input text :


I want to put a default value like

13条回答
  •  一生所求
    2020-11-29 18:45

    Using jQuery, you can do:

    $("input:text").each(function ()
    {
        // store default value
        var v = this.value;
    
        $(this).blur(function ()
        {
            // if input is empty, reset value to default 
            if (this.value.length == 0) this.value = v;
        }).focus(function ()
        {
            // when input is focused, clear its contents
            this.value = "";
        }); 
    });
    

    And you could stuff all this into a custom plug-in, like so:

    jQuery.fn.hideObtrusiveText = function ()
    {
        return this.each(function ()
        {
            var v = this.value;
    
            $(this).blur(function ()
            {
                if (this.value.length == 0) this.value = v;
            }).focus(function ()
            {
                this.value = "";
            }); 
        });
    };
    

    Here's how you would use the plug-in:

    $("input:text").hideObtrusiveText();
    

    Advantages to using this code is:

    • Its unobtrusive and doesn't pollute the DOM
    • Code re-use: it works on multiple fields
    • It figures out the default value of inputs by itself



    Non-jQuery approach:

    function hideObtrusiveText(id)
    {
        var e = document.getElementById(id);
    
        var v = e.value;
    
        e.onfocus = function ()
        {
            e.value = "";
        };
    
        e.onblur = function ()
        {
            if (e.value.length == 0) e.value = v;
        };
    }
    

提交回复
热议问题