如何在jQuery中保留任何文本框的文本

时间:2011-09-21 18:33:12

标签: jquery asp.net

我有多个具有相同类“.input”的文本框。每个文本框都有不同的默认文本:名字,姓氏等......

在特定文本框的焦点上,我希望默认文本消失,并将“.focus”类添加到文本框中。关于该文本框的模糊,如果用户没有输入任何文本,我希望返回默认文本。除非用户输入文字,否则我也希望删除“.focus”类。

我知道如何为一个文本框执行此操作,但不知道多个文本框(不为每个文本框编写函数)。我猜有办法。

我也在使用asp.NET文本框,所以我不得不修改选择器。

var myText
var myBox
$('input:text.input').focus(function () {
    myText = $(this).val();
    myBox = $(this);
    //alert('focus');
}).blur(function () {
    alert($(myText).val());
});

我很确定全局变量在调用模糊函数时不会保留它们的值。我已经在多个网站上多次看到过这种情况,我无法弄明白。

感谢任何帮助。谢谢!

我已经搜索并提出了一些关闭...然而,当调用模糊时,即使我输入了文本,默认文本也会消失。

        $('input:text.input').focus(function () {

        if (this.value == this.defaultValue) {
            this.value = '';
        }
        if (this.value != this.defaultValue) {
            this.select();
        }
    });
    $('input:text.input').blur(function () {
        $(this).removeClass("focus");
        if ($.trim(this.value == '')) {
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });

感谢您的帮助!这是带有一些调整的代码。

    $('input:text.input').focus(function () {
       if($(this).hasClass('focus')) { } else {
         $(this)
           .data('stashed-value', $(this).val()) // stash it
           .addClass('focus')
           .val(''); // clear the box
        }
    }).blur(function () {
       if ($(this).val() != '') { } else {
         $(this)
           .val($(this).data('stashed-value')) // retrieve it
           .removeClass('focus');
        }
});

3 个答案:

答案 0 :(得分:3)

一种方法是使用data()隐藏您要在元素内保存的值:

$('input:text.input').focus(function () {
    $(this)
      .data('stashed-value', $(this).val() ) // stash it
      .val(''); // clear the box
}).blur(function () {
    // presumably you'll check some conditions here (e.g. input empty) then:
    $(this).val( $(this).data('stashed-value') ); // retrieve it
});

答案 1 :(得分:1)

如果您使用的是HTML5,占位符文字会为您执行此操作:

<input name="q" placeholder="Search Bookmarks and History">

http://diveintohtml5.ep.io/forms.html#placeholder

您可以在Chrome或FF中查看。

您也可以使用jQuery

执行此操作
$('input').focus(function(){
    if($(this).val() == 'Search'){
        $(this).val('');
    }
});

$('input').blur(function(){
    if($(this).val() == ''){
        $(this).val('Search')
    }
});

示例: http://jsfiddle.net/jasongennaro/YaXSg/

答案 2 :(得分:0)

您可以实现这些答案的组合,以创建适用于HTML5兼容浏览器的解决方案,并优雅降级其他浏览器。

HTML5:

<input type='text' placeholder="First Name" class="input" />
<input type='text' placeholder="Last Name" class="input" />
<input type='text' placeholder="Email" class="input" />

用于向后兼容的jQuery代码:

$('input:text.input').each(function (i) {
    $(this).val($(this).attr('placeholder'));
    $(this).focus(function() {
        if ($(this).val() == $(this).attr('placeholder'))
        {
            $(this).val('');
        }
    });
    $(this).blur(function() {
        if (!$(this).val())
        {
            $(this).val($(this).attr('placeholder'));
        }
    });
});
相关问题