用jquery或其他工具在textarea中倒计时可用空间? [英] Countdown available spaces in a textarea with jquery or other?

查看:79
本文介绍了用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天全站免登陆