How to set textarea input counter

I have a text area with a certain width and height, so how to create a message counter and set the maximum letters printed in the text box should not exceed 100 words.

HTML

<div class="box">
<textarea name="" id=""></textarea>
<div class="word-counter">0/100</div>
</div>

CSS

.box {
width:500px;
border: 1px solid red;
position:relative;
display:table;
}
textarea {
width:500px;
height:80px;
padding-bottom: 20px;
}
.word-counter {
position:absolute;
bottom: 0;
right:0;
}
+4
source share
5 answers

Use to count letters. .keyup()

$('#area').keyup(function(){
    $('.word-counter').text($.trim(this.value.length)+'/100');
})

And an attribute maxlengthfor maximum letters.

<div class="box">
<textarea name="" id="area" maxlength="100"></textarea>
<div class="word-counter">0/100</div>
</div>

Demo script

* Note. This supports spaces. If you need to handle only the number of letters, you can control keyup().

$('#area').keyup(function(){
    $('.word-counter').text(this.value.replace(/ /g,'').length+'/100');
})

Fiddle (spaces are ignored in the number of letters)

+3
source

maxlength, , , . , JavaScript.

1000 , , / .

HTML

<div class="box">
<textarea name="" id="" maxlength="50"></textarea>
<div class="word-counter">0/100</div>
</div>
+2

You can perform this function:

function countwords(str){
  var count = 0;
  str=str.trim();
  for (var i = 0; i <= str.length; i++) {
     if (str.charAt(i) == " ") {
        count ++;
      }
  }
  return count;
}
+1
source

try it

$('#text').keydown(function(e){
    var code=e.keyCode;
    var length=$(this).val().split(' ').length;
    if(length<=100)
    {
        $('.word-counter').text(length+'/100');
    }
    else
    {
        if(code!=37&&code!=38&&code!=39&&40&&code!=8&&code!=46)
        {
        return false;
        }
    }
});

Working demo

+1
source
$('#text').keyup(function(e) {
    var length=parseInt($(this).val().length)+1;
     switch (e.keyCode) {
            case 8:  // Backspace
            length--;
             $('.word-counter').text(length+'/100');
             break;
            case 9:  // Tab
            case 13: // Enter
            case 37: // Left
            case 38: // Up
            case 39: // Right
            case 40: // Down
            break;

            default:
                 if(length<=100)
                {
                    $('.word-counter').text(length+'/100');
                }
                else
                {
                    return false;
                }
        }         
    });

Use keyup()to count the letters.
This is his working demo. Working demo.

0
source

Source: https://habr.com/ru/post/1588924/


All Articles