Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the textarea input letters counter [duplicate]

Tags:

html

jquery

css

I've an textarea with a specific width and height so how do I create a letter counter and set the maximum letters typed in the textarea should not be more than 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;
}
like image 780
Firnas Avatar asked Jan 09 '23 08:01

Firnas


1 Answers

Use .keyup() for counting letters.

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

And maxlength attribute for max letters.

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

Demo Fiddle

*Note : This supports spaces. If you need to handle just letter count the keyup() can be manipluated.

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

Fiddle (Spaces ignored in letter count)

like image 102
Shaunak D Avatar answered Feb 04 '23 16:02

Shaunak D