Max characters in textarea with jquery

前端 未结 16 1834
逝去的感伤
逝去的感伤 2020-12-03 04:53

I have the following code, and I\'m kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left.

16条回答
  •  误落风尘
    2020-12-03 05:15

    I know this is a little late, but I just had to figure this out, too. I had to get it to work with UTF8 byte-lengths, and allow certain keypresses. Here's what I came up with:

    checkContent = function (event) {
    
        var allowedKeys = [8,46,35,36,37,38,39,40];
        var contentLength = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
        var charLength = lengthInUtf8Bytes(String.fromCharCode(event.charCode));
    
        if (charLength + contentLength > 20) {
    
            if(jQuery.inArray(event.keyCode, allowedKeys) == -1) {
                event.preventDefault();
            } 
        }
    }
    
    countLength = function(event) {
    
        var len = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
        jQuery('#length').html(len);
    }
    
    
    lengthInUtf8Bytes = function(str) {
        var m = encodeURIComponent(str).match(/%[89ABab]/g);
        return str.length + (m ? m.length : 0);
    }
    
    jQuery(function(){jQuery("#textarea").keypress(function(event){checkContent(event)}).keyup(function(event){countLength(event)})});
    

    You need to have a textarea with id #textarea and an element to display the current length with id #length.

    The keypress event determines whether or not to allow the keypress. The keyup event counts the size of the data in the field after the keypress is allowed/prevented.

    This code works with the following keys: home, end, pagedown, pageup, backspace, delete, up, down, left and right. It doesn't deal with pasting from the clipboard.

    Hope someone finds it useful!

提交回复
热议问题