Max characters in textarea with jquery

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

    Relying on keypress, keydown, keyup is a flawed solution because a user can copy and paste data into the textarea without pressing any keys.

    To limit the length of text in a textarea with javascript regardless of how the data gets in there you must rely on a setInterval timer instead.

    setInterval(function() {
    if ($('#message').val().length > 250) {
        $('#message').val($('#message').val().substring(0, 250));
    }}, 500);
    

    Obviously, I'm assuming you have an id of message assigned to your textarea.

提交回复
热议问题