textarea jQuery上的默认文本? [英] Default text on textarea jQuery?

查看:85
本文介绍了textarea jQuery上的默认文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个textarea,我想在页面加载时显示一些默认文本。单击textarea后,我希望文本消失,如果用户在textarea中单击并且没有输入任何内容然后单击textarea,则默认文本将再次显示。

I have a textarea that i would like to show some default text on page load. Once the textarea is clicked i would like to have the text disappear and possibly if user clicked in textarea and did not type anything in and then clicked out of textarea the default text will show again.

我搜索了谷歌并在这里,但我似乎只能找到与文本框和 NOT textareas相关的教程,而且我已经在textarea上使用了一个类,所以不能依赖于类它可以工作。

I have searched Google and on here but i can only seem to find tutorials relating to text boxes and NOT textareas, plus i already am using a class on the textarea so cannot depend on class for it to work.

有没有人想要与我分享一些简单的jQuery代码来做我想要的事情?

Does anyone have some simple jQuery code they would like to share with me to do what i want above?

推荐答案

DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/

重要的是要记住用户输入值的边缘情况默认。我的解决方案是通过使用jQuery的 data() c> 一个编辑的标志来避免这种情况。 code>方法。

It is important to remember the edge case that the user types the value which is your default. My solution avoids this by giving each textarea an edited flag using jQuery's data() method.

定义 textarea

<textarea>This is the default text</textarea>



jQuery



The jQuery

$('textarea').each(function() {
    // Stores the default value for each textarea within each textarea
    $.data(this, 'default', this.value);
}).focus(function() {
    // If the user has NOT edited the text clear it when they gain focus
    if (!$.data(this, 'edited')) {
        this.value = "";
    }
}).change(function() {
    // Fires on blur if the content has been changed by the user
    $.data(this, 'edited', this.value != "");
}).blur(function() {
    // Put the default text back in the textarea if its not been edited
    if (!$.data(this, 'edited')) {
        this.value = $.data(this, 'default');
    }
});

DEMO: http://jsfiddle.net/marcuswhybrow/eJP9C/2/

这篇关于textarea jQuery上的默认文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆