0

My task is to create a counter/limiter, which pops a window when the limit is reached. I made this code:

$(document).ready(function() {
    $('#message-input').keyup(updateCounter);
});

function updateCounter() {

    var value = $('#message-input').val();

    if (value.length > 256) {
        alert('Túl hosszú az üzenet!');
        return false;
    }

    var remaining = 256 - value.length;
    $('#counter').text(remaining);

    return true;
}

This code works great, but has a big problem: if the limit is reached, i can press anything, always the window pops up, even if i press backspace. How can i correct that?

4

2 回答 2

1

尝试这个:

$(document).ready(function() {
    $('#message-input').keyup(updateCounter);
});

function updateCounter(e) {
    if( $inArray(e.which, [8, 37, 38, 39, 40])) return true; // If keycode = backspace, left, top, right, bottom array, than continue.

    var value = $('#message-input').val();

    if (value.length > 256) {
        alert('Túl hosszú az üzenet!');
        return false;
    }

    var remaining = 256 - value.length;
    $('#counter').text(remaining);

    return true;
}
于 2013-04-14T10:29:38.643 回答
1

您可以删除最后一个字母以保持 256 个字符的长度,例如使用子字符串。

于 2013-04-14T10:30:11.890 回答