文本框按键字数在过去的单词时不起作用

时间:2014-10-09 20:48:19

标签: javascript jquery

我试图在文本框中只允许300个单词。它工作正常,但是当我粘贴它不起作用。我需要在粘贴后修剪300个单词,不允许超过300个单词。

我的代码中需要更改哪些内容?

var max = 300;
var maxWords = "Words Max: 300";
$('#AbstractTextText').keypress(function (e) {
    var val = $.trim($('#AbstractTextText').val()), // Remove spaces from b/e of string
        words = val.replace(/\s+/gi, ' ').split(' ').length, // Count word-splits
        chars = val.length;

    if (words < max) {
        $('#spanWordCnt').text((max - words) + ' words remaining (' + maxWords + ').');
        // e.which < 0x20, then it's not a printable character
        // e.which === 0 - Not a character
        return;     // Do nothing
    }
    if (words == max) {
        $('#spanWordCnt').text((max - words) + ' words remaining (' + maxWords + ').');
        e.preventDefault();
    } else if (words > max) {
        alert(this.value.substring(0, chars));
        $('#spanWordCnt').text((max - words) + ' words remaining (' + maxWords + ').');
        // Maximum exceeded
        this.value = this.value.substring(0, chars);
    }
});

2 个答案:

答案 0 :(得分:0)

您可以使用on

来举办paste活动
var maxWords = 300;
$("#AbstractTextText").on("paste", function (event) {
    setTimeout(function () {
        var text = $("#AbstractTextText").val().split(" ");
        while (text.length > maxWords) {
            text.pop();
        }
        $("#AbstractTextText").val(text.join(" "));
    }, 0)
})

这只会说明你仍然需要你的keyup事件的粘贴内容。

答案 1 :(得分:0)

您可以一起使用以下三个事件:

var maxAmountOfCharacters = 300;

$('texarea').on('change keyup paste', function(e) {
    ... // do things
});