达到最大字符数限制后如何防止用户在文本区域中输入文本 [英] How to prevent user to enter text in textarea after reaching max character limit

查看:89
本文介绍了达到最大字符数限制后如何防止用户在文本区域中输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要阻止用户在达到最大字符数限制后在textarea中输入文本.发生了什么事,当我达到最大限制时,我的文本区域滚动条移到了顶部,因此我用这种代码以某种方式阻止了这种情况.

I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code.

jQuery(document).ready(function($) {
    $('textarea.max').keyup(function() {
        var $textarea = $(this);
        var max = 400;
        if ($textarea.val().length > max) {
            var top = $textarea.scrollTop();
            $textarea.val($textarea.val().substr(0, max));
            $textarea.scrollTop(top);

        }
    });
}); //end if ready(fn)

但是我也希望达到最大限制后,用户无法在textarea中键入任何内容.当前,如果用户按下并按住键达到最大限制后,字符将在文本区域中键入,尽管释放按钮后它将返回原始文本(即$ textarea.val($ textarea.val(). substr(0,max));).但是我希望一旦这种情况成为现实

But i also want that after reaching max limit user unable to type anything in the textarea. Currently what happen that after reaching max limit if user press and hold the key, the characters are typing in the text area, although after releasing the button it come back to original text (i.e $textarea.val($textarea.val().substr(0, max)); ). But i want that once this condition become true

if ($textarea.val().length > max) {

用户无法输入任何内容.我希望光标从文本区域中消失.但是,如果用户删除了一些文本,则光标也可供用户再次输入.我该怎么办?

user unable to type anything. I want that cursor vanishes from the textarea. But if user remove some text then cursor also available for user to type input again. How can I do it?

推荐答案

发生默认行为(填充文本区域)后,将触发keyup事件.

The keyup event fires after the default behaviour (populating text area) has occurred.

最好使用keypress事件,并过滤不可打印的字符.

It's better to use the keypress event, and filter non-printable characters.

演示: http://jsfiddle.net/3uhNP/1/ (最大长度为4)

Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)

jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)

这篇关于达到最大字符数限制后如何防止用户在文本区域中输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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