Max characters in textarea with jquery

前端 未结 16 1669
逝去的感伤
逝去的感伤 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/

    0 讨论(0)
  • 2020-12-03 05:20

    try this.

    var charLmt = "200";//max charterer 
     $("#send-txt").keydown(function(){
       var _msgLenght = $(this).val().length;
       if (_msgLenght > charLmt) {
       $(this).val($(this).val().substring(0, charLmt));
      }
    });
    
    0 讨论(0)
  • 2020-12-03 05:21

    Got it with this:

    $("#div_id").prop('maxlength', '80');
    

    I really dont know if there's something wrong with this solution, but it worked for me.

    0 讨论(0)
  • 2020-12-03 05:22

    Here's a solution using HTML5 data attribute to automatically bind to all needed textareas:

    $('textarea[data-max-length]').live('keypress', function(e) {
        if (String.fromCharCode(e.charCode || e.keyCode).match(/\S/) && $(this).val().length >= $(this).attr('data-max-length')) {
            e.preventDefault();
        }
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 05:25

    Here it goes. Anything beyond character limit will be removed.

    $('textarea').keypress(function(e) {
        var tval = $('textarea').val(),
            tlength = tval.length,
            set = 10,
            remain = parseInt(set - tlength);
        $('p').text(remain);
        if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
            $('textarea').val((tval).substring(0, tlength - 1));
            return false;
        }
    })
    

    Check working example at http://jsfiddle.net/JCehq/1/

    0 讨论(0)
提交回复
热议问题