Max characters in textarea with jquery

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

    If you change your js to look like this it should work for you:

    var $txtLenLeft = $('#txt-length-left'); // lets cache this since it isn't changing
    $('#send-txt').keydown(function(e) { //take the event argument
       var Length = $(this).val().length; // lets use 'this' instead of looking up the element in the DOM
       var AmountLeft = maxLen - Length;
       $txtLenLeft.html(AmountLeft);
       if(Length >= maxLen && e.keyCode != 8){ // allow backspace
          e.preventDefault(); // cancel the default action of the event
       }
    });
    

    You can see a working example here: http://jsfiddle.net/aP5sK/2/

提交回复
热议问题