使用 jquery 或其他方式对 textarea 中的可用空间进行倒计时? [英] Countdown available spaces in a textarea with jquery or other?

查看:19
本文介绍了使用 jquery 或其他方式对 textarea 中的可用空间进行倒计时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有几个区域需要将文本输入限制为 X 个字符,并且在用户输入时显示一些剩余的空格非常好,就像 twitter 那样.

I have a few areas on my site where I need to limit text input to X amount of characters and it's nice to show a number of spaces left while a user types in, like twitter does.

我找到了这个 jquery 插件;jquery 最大长度插件

I found this jquery plugin; jquery max-length plugin

它正好满足了我的需要,但似乎有点矫枉过正,我不确定文件大小,但对于这样一个简单的任务,它看起来像很多行代码,你认为我最好使用非-jquery 方法?我认为 jquery 是要走的路的原因是因为 jquery 已经包含在我的所有页面中更新;

It does just what I need but it seems kind of like overkill, I am not sure the filesize but it looks like a lot of lines of code for such a simple task, do you think I would be better off using a non-jquery method? The reason I was thinking jquery was the way to go is because jquery is already included into all my pages UPDATE;

我刚刚发现这种完全相同的非 jquery 方法占用的空间更小,所以这会是更好的方法吗?

I just found this non-jquery method that does the exact same thing is is way smaller footprint, so would this be the better method?

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
   if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
   } else {
    limitCount.value = limitNum - limitField.value.length;
   }
}
</script>

You have 
<input readonly type="text" name="countdown" size="3" value="1000">
characters left.

推荐答案

在 jQuery 中非常简单:

Very simple in jQuery:

<textarea id="myTextarea"></textarea>
<p id="counter"></p>

<script type="text/javascript">
$('#myTextarea').keyup(function () {
    var left = 200 - $(this).val().length;
    if (left < 0) {
        left = 0;
    }
    $('#counter').text('Characters left: ' + left);
});
</script>

用你的极限代替 200.

Substitute the 200 by whatever your limit is.

注意这不限制实际的文本输入,它只是倒计时.您需要检查服务器端的输入长度,这只是一个视觉助手.

Note this does not limit the actual text input, it just counts down. You need to check server-side for the input length, this is just a visual helper.

顺便说一句,我认为您甚至不应该尝试通过在达到限制时拒绝任何输入来限制输入长度.这是后方可用性方面的痛苦,无论如何都不能依赖.恕我直言,简单的倒计时和服务器端检查是最好的选择.

As an aside, I don't think you even should try to limit the input length by denying any input when the limit is reached. It's a pain in the rear usability-wise and can't be relied upon anyway. A simple countdown and server-side checking is the best option IMHO.

这篇关于使用 jquery 或其他方式对 textarea 中的可用空间进行倒计时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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