Countdown available spaces in a textarea with jquery or other?

后端 未结 9 1168
無奈伤痛
無奈伤痛 2020-12-07 19:17

I have a few areas on my site where I need to limit text input to X amount of characters and it\'s nice to show a number of spaces left while a user types in, like twitter d

相关标签:
9条回答
  • 2020-12-07 19:53

    So I took @deceze version and added a bit of trick to make it:

    • show always and not only when the user starts typing,
    • show minus when the limit is over, and
    • add class - to color the text - when it is over the limit (extra css is needed for this of course)

      $(document).ready(function(){
          var left = 200
          $('#field_counter').text('Characters left: ' + left);
      
              $('#id_description').keyup(function () {
      
              left = 200 - $(this).val().length;
      
              if(left < 0){
                  $('#field_counter').addClass("overlimit");
              }
              if(left >= 0){
                  $('#field_counter span').removeClass("overlimit");
              }
      
              $('#field_counter').text('Characters left: ' + left);
          });
      });
      

    For anyone needing the same as me :)

    0 讨论(0)
  • 2020-12-07 19:53

    Using jQuery, assuming that you have a textarea with id field that you wish to limit to 100 characters, and another element with id chars-remaining to display the number of available characters:

    var max = 100;
    $('#field').keyup(function() {
        if($(this).val().length > max) {
            $(this).val($(this).val().substr(0, max));
        }
        $('#chars-remaining').html((max - $(this).val().length) + ' characters remaining');
    });
    
    0 讨论(0)
  • 2020-12-07 20:00

    Keep in mind that you have to account for NewLines being 2 characters.
    I built upon the solutions provided here to the below code which accounts for new lines.

    function DisplayCharactersLeft(idOfInputControl) {
        var maxNumberOfCharacters = $("#" + idOfInputControl).attr("maxLength");
    
        $("#" + idOfInputControl).on("input", function () {
            var currentText = $(this).val();
            var numberOfNewLines = GetNumberOfNewLines(currentText);
    
            var left = maxNumberOfCharacters - (currentText.length + numberOfNewLines);
            if (left < 0) { left = 0; }
            $("#" + idOfInputControl + "CharactersLeftCounter").text("Characters left: " + left);
        });
    
    }    
    
    function GetNumberOfNewLines(text) {
    
        var newLines = text.match(/(\r\n|\n|\r)/g);
        var numberOfNewLines = 0;
        if (newLines != null) {
            numberOfNewLines = newLines.length;
        }
        return numberOfNewLines;
    }
    
    0 讨论(0)
提交回复
热议问题