Wed. Nov 20th, 2019

Codes

Codes for Coders

Really simple jQuery character countdown in textarea

1 min read
character count by himanshu

character count by himanshu

Looking to build a Twitter-like textarea character countdown to show your users how much space they have remaining?

character count by himanshu

 

HTML:

<form method="post" enctype="multipart/form-data" action="">
<textarea onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)" name="countt" rows="8" cols="40"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
<p><strong><span id="charCount">1160</span></strong> more characters available.</p>

Jquery:


var maxLength=1160;
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) charCount.innerHTML = maxLength - el.value.length;
return true;
}

I’ve seen a few tutorials online but they seem to make it more complex than it needs to be. Just a few lines of jQuery does the trick.

1. Set a variable for the max number of characters:

var maxLength = 1160;
2. Use the keyup event on the textarea, which fires each time a key is pressed when the textarea is in focus. Ideal:

onKeyUp=”return characterCount(this)”

3. Check the value and get the length of it:

maxLength – el.value.length;

4. Put the result somewhere on the page:

charCount.innerHTML = maxLength – el.value.length

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *