实时显示用户输入时HTML textarea中的字符数 [英] Show in real time the number of characters in a HTML textarea while the user types

查看:280
本文介绍了实时显示用户输入时HTML textarea中的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 textarea 跨度创建博客评论表格 它向用户显示可以在文本区域中引入的剩余字符数。



所以我有这种形式:

 < form action =comment.phpmethod =POSTaccept-charset =utf-8> 
< textarea name =commentid =commentrows =4cols =56>< / textarea>

< input type =submitvalue =发布/>
< span id =comment-chars-left> 512< / span>字符剩余
< / form>

然后我写了下面的jQuery代码:

  $('#comment')
.keydown(function(event){
$('#comment-chars-left')。html(' '+(512 - $ textarea.val()。length));
});

问题是,当输入 .keydown 首先被调用,它打印剩余字符的数量,然后在 textarea 中显示输入的新字符。所以剩余字符的数量没有一个正确的值,大一个单位。在插入新字符后,应该调用 .keydown



如何解决这个问题问题?

解决方案

使用 keyup()代替。



您还需要绑定其他一些事件。使用 bind('keyup paste drop ')



keyup 如果有人将文本粘贴到 textarea 中,并且 drop ,则粘贴您的 textarea 中的文字块。



jsFiddle


I am trying to create a blog comment form with a textarea and a span which shows to the user the number of remaining characters that can be introduced in the text area.

So I have this form:

<form action="comment.php" method="POST" accept-charset="utf-8">
    <textarea name="comment" id="comment" rows="4" cols="56"></textarea>

    <input type="submit" value="Post" />
    <span id="comment-chars-left">512</span> characters left
</form>

And then I wrote the following jQuery code:

$('#comment')
    .keydown(function(event) {
        $('#comment-chars-left').html('' + (512 - $textarea.val().length));
    });

The problem is that when typing .keydown is called first, which prints the number of remaining characters and then the new character typed is shown in the textarea. So the number of remaining characters does not have a correct value, being bigger by one unit. To make this work .keydown should be called after the insertion of the new character.

How can I resolve this problem?

解决方案

Use keyup() instead.

You will also want to bind a few other events.

Use bind('keyup paste drop').

keyup for event when key is released, paste if someone pastes text in your textarea, and drop if someone drops a chunk of text in your textarea.

jsFiddle.

这篇关于实时显示用户输入时HTML textarea中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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