Viktor
Viktor

Reputation: 722

Textarea count characters not working as needed

I have simple script character counter, but i cannot understand why it's showing that it's 5 or any other number less than 10, as remaining characters.It must show that it's "0" characters remaining and also it's not counting if i paste some text into text area. How can i fix this?

HTML CODE

<textarea name="" id="txtarea" cols="30" rows="10"></textarea>
<p id="demo"></p>

JS CODE

var txt = document.getElementById("txtarea");
txt.setAttribute("maxlength", 50)
var maxLength = 50;
var demo = document.getElementById("demo");
var checkLength = function(){
    if(txt.value.length < maxLength) {
        var result = demo.innerHTML =  " Character remaining: " + (maxLength-txt.value.length) 
    };  
};
setInterval(checkLength, 300);

Upvotes: 0

Views: 600

Answers (4)

Poul Kruijt
Poul Kruijt

Reputation: 71901

If you type fast it will never show 4 or 5 characters remaining. A better solution would be to put an onchange event on it. And yes, it should be <= :)

Upvotes: 1

jolmos
jolmos

Reputation: 1575

Here is the problem: if(txt.value.length < maxLength)

Should be: if(txt.value.length <= maxLength)

Anyway, I wouldn't do it with a time interval but on the keyDown event. Something like this:

var txt = document.getElementById("txtarea");
txt.setAttribute("maxlength", 50)
var maxLength = 50;
var demo = document.getElementById("demo");
var checkLength = function(){
    if(txt.value.length <= maxLength) {
        var result = demo.innerHTML =  " Character remaining: " + (maxLength-txt.value.length) 
    };  
};
<textarea name="" id="txtarea" cols="30" onKeyDown="checkLength()" rows="10"></textarea>
<p id="demo"></p>

Upvotes: 1

eLGi
eLGi

Reputation: 100

One, as @jolmos said, you have to check if it is less or EQUAL to. You are just checking if this is less than so it will never show "0" as remaining characters number.

Two, about that not counting when paste try to bind this checkLength() function to keyup/keydown event instead of calling it from interval.

Try this:

txt.addEventListener("keyup", function() {
if(txt.value.length <= maxLength) {
    var result = demo.innerHTML =  " Character remaining: " + (maxLength-txt.value.length) 
};
}

Upvotes: 1

Aides
Aides

Reputation: 3673

Apart from the fact that it should be txt.value.length <= maxLength this should be working perfectly fine (check out this fiddle https://jsfiddle.net/Aides/nc39hsng/)

Also you might use onkeyup and onchange instead of setInterval

Upvotes: 0

Related Questions