Clear input on focus with jQuery and return on blur

后端 未结 12 2306
耶瑟儿~
耶瑟儿~ 2021-02-09 17:50

This almost works. However, when leaving the field \"defaulttext\" appears rather than the original text value. Not sure how to most efficiently echo the variable inside default

相关标签:
12条回答
  • 2021-02-09 18:35
    var q = $('#q');
    q.focus(function() {
        if ($(this).attr('data-default') == $(this).val()) {
            $(this).val('');
        }
    }).blur(function() {
        if($(this).val() == '') {
            $(this).val($(this).attr('data-default'));
        }
    });
    
    
    <input type="text" name="q" id="q" data-default="Search..." value="Search..."/>
    
    0 讨论(0)
  • 2021-02-09 18:37

    You need to remove the ' ' marks around the defaultText variable in your set method (val).

    Try something along hte lines of

    $(function() {
        var defaultText = '';
        $('input[type=text]').focus(function() {
            defaultText = $(this).val();
            $(this).val('');
        });
        $('input[type=text]').blur(function() {
            $(this).val(defaultText); // NB removed the ' ' marks
            //echo // What are you trying to echo? 
         });
     });
    
    0 讨论(0)
  • 2021-02-09 18:37

    This one will save the default text for you using the .data() function. So no need for extra markup.

    $('input').focus(function() {
        if (!$(this).data("DefaultText")) $(this).data("DefaultText", $(this).val());
        if ($(this).val() != "" && $(this).val() == $(this).data("DefaultText")) $(this).val("");
    }).blur(function(){
        if ($(this).val() == "") $(this).val($(this).data("DefaultText"));
    });
    
    0 讨论(0)
  • 2021-02-09 18:39

    I funetuned this code little bit.

    $(document).ready(function () {
        var defaultText = '';
        $('.input-focus-clear').focus(function () {
            defaultText = $(this).val();
            $(this).val('');
        });
        $('.input-focus-clear').blur(function () {
            var newText = $(this).val();
            if (newText.length < 1) {
               $(this).val(defaultText);
            }
        });
    });
    
    0 讨论(0)
  • 2021-02-09 18:40

    Use HTML5 attribute placeholder on each input tag, eg:

    <input type="text" value="original text value" placeholder="default value" />
    
    0 讨论(0)
  • 2021-02-09 18:42

    You're not referencing the variable defaultText. You're passing a string since it's wrapped in quotes.

    $(function() {
        var defaultText = $('input[type=text]').val();
        $('input[type=text]').focus(function() {
          $(this).val('');
          });
         $('input[type=text]').blur(function() {
          $(this).val(defaultText); // fixed!
          });
     });
    
    0 讨论(0)
提交回复
热议问题