空文本框上的JQuery默认文本

时间:2011-01-22 21:07:42

标签: javascript jquery html textbox

我有一个电子邮件表单文本框,虽然它是空的我希望它有值“电子邮件”当你点击它时文本消失了。如果有人点击它并且没有输入文字。在Blur上我想让它返回到默认文本。

我一直在尝试一些事情,但没有任何工作。有人可以指出我正确的方向吗?

7 个答案:

答案 0 :(得分:20)

或者您可以使用占位符html5属性:

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

答案 1 :(得分: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');
    }
});

答案 2 :(得分: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 :(得分:3)

It's pretty straightforward.只需删除值onfocus,然后(如果值仍为空)重新填充onblur

答案 4 :(得分:1)

调用以下函数并传递两个args: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'));
            }
        });

    }

答案 5 :(得分: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" />

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

答案 6 :(得分:1)

使用此Jquery-placeholder插件

使用此插件可以在非HTML5浏览器中使用占位符属性。

相关问题