jQuery在空文本框上设置默认文本

7

我有一个电子邮件表单文本框,当它为空时,我希望它的值为“电子邮件”,当您点击它时,文本消失。如果有人点击它并没有输入文本,在失去焦点时,我希望它返回到默认文本。

我已经尝试了一些方法,但没有任何作用。请问有谁能指点我正确的方向吗?

7个回答

20

或者你可以直接使用HTML5的占位符属性:

<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" />

不知道 placeholder 属性。很棒的补充!:) 很遗憾目前 IE 不支持它(IE 9)。 - Leniel Maccaferri
16
人们还认为IE是一款网络浏览器吗? - webtweakers
1
到目前为止,所有浏览器都支持占位符属性:https://caniuse.com/input-placeholder (甚至是IE!) - webtweakers

9

它大概是这样的

$('#yourElement').focus(function(){
    //Check val for email
    if($(this).val() == 'E-Mail'){
        $(this).val('');
    }
}).blur(function(){
    //check for empty input
    if($(this).val() == ''){
        $(this).val('E-Mail');
    }
});

5

您可以使用占位符属性,然后使用此jQuery作为IE的备用方案。

<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/>

$(document).ready(function () {
    $('.watermark').focus(function () {
        if ($(this).val() == $(this).attr('placeholder')) {
            $(this).val('');
        }
    }).blur(function () {
        if ($(this).val() == '') {
            $(this).val($(this).attr('placeholder'));
       }
    });
});

3

这很简单。只需删除onfocus的值,然后(如果该值仍为空)在onblur中重新填充它。


这个例子还会删除输入框中新输入的文本,这并不是你想要的。 - webtweakers

1
调用下面的函数并传递两个参数:slightLabel(jQuery('#email_field'), 'email');
  function slightLabel(input, text) {
        jQuery(input).val(text);
        jQuery(input).data('defaultText', text);
        jQuery(input).focus(function(){
            if(!jQuery(this).data('touched'))
            {
                jQuery(this).data('touched', true);
                jQuery(input).val('');
            }
        });

        // the part to restore the original text in
        jQuery(input).blur(function(){
            if(jQuery(this).val() == '')
            {
                jQuery(this).val(jQuery(this).data('defaultText'));
            }
        });

    }

1
你可以使用jQuery的一个水印插件来实现这个功能。我使用了一个水印插件,它的代码如下:
$.fn.watermark = function (c, t) {
var e = function (e) {
    var i = $(this);
    if (!i.val()) {
        var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
        i.replaceWith($c);
        $c.focus(function () {
            $c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
        })
            .change(function (e) {
                i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
            })
            .closest('form').submit(function () {
                $c.replaceWith(i);
            });
    }
};
return $(this).live('blur change', e).change();

};

将输入文本框的类设置为水印,即可在jquery中调用。

<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
    title="Type keyword here" />

标题是将显示在水印中的内容。


1

使用Jquery-placeholder插件。

使用此插件可以在不支持HTML5的浏览器中使用占位符属性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接