【问题标题】:Maxlength validation not including line break or list (spaces) pasted from word using Jquery?Maxlength验证不包括使用Jquery从单词粘贴的换行符或列表(空格)?
【发布时间】:2013-04-01 20:14:16
【问题描述】:

我有以下 Jquery 验证将文本限制为 400 最大长度。它适用于纯文本,但从包含换行符、间距等格式的单词粘贴时似乎不起作用。 =

$('textarea[maxlength]').keyup(function(){
                //get the limit from maxlength attribute
                var limit = parseInt($(this).attr('maxlength'));
                //get the current text inside the textarea
                var text = $(this).val();
                //count the number of characters in the text
                var chars = text.length;

                //check if there are more characters then allowed
                if(chars > limit){
                    //and if there are use substr to get the text before the limit
                    var new_text = text.substr(0, limit);

                    //and change the current text with the new text
                    $(this).val(new_text);
                }

【问题讨论】:

    标签: jquery textarea validation maxlength


    【解决方案1】:

    试试这个...

    function validateLength(textareaElement) {
        // your logic here, use textareaElement instead of $(this)
    }
    $('textarea[maxlength]').keyup(function(eventObject) {
        window.setTimeout(function() {
            validateLength($(eventObject.target));
        , 1);
    });
    

    1 毫秒的超时应该足以“逃脱 keyup 事件的内部范围”,并允许您获取 textareaElement 的正确字符串值。

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2018-05-11
      • 1970-01-01
      • 2020-07-19
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多