Max characters in textarea with jquery

前端 未结 16 1802
逝去的感伤
逝去的感伤 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:10

    All of these answers are a bit odd in that they try to do a little too much. A simpler and visually more pleasing way (because it shows the text quickly being cut off) - and with with less oddities that the previous example (note how it overwrites the final key?) - is to simply cut off the number of characters on keyUp to the number that's allowed.

    var maxchars = 400;
    
    $('body').on('keyup paste', 'textarea', function () {
        $(this).val($(this).val().substring(0, maxchars));
        var tlength = $(this).val().length;
        remain = maxchars - parseInt(tlength);
        $('#remain').text(remain);
    });
    

    Note that this then also works for pasting in text, as some of the examples above don't.

    Example here: http://jsfiddle.net/PzESw/5/

提交回复
热议问题