How to count characters remaining with jQuery?

Today, we are going to take a look at a simple jQuery snippet which can count the number of characters the user has entered in the textarea and display the remaining character count, that he/she can input. You may have seen this type feature in twitter while creating a new tweet.

Count Characters Remaining with jQuery

Count Characters Remaining with jQuery

See Also: How to select / deselect all checkboxes using jQuery?

jQuery:

$(document).ready(function(){
	var totalChars = $('#remaining').text();
	var inputChars = $('#sampleText').val();
	var remainChars = totalChars;
	$('#sampleText').on('keyup',function(){
		var inputChars = $(this).val().length;
		remainChars = totalChars - inputChars;
		$('#remaining').text(remainChars);
	})
})

 HTML:

<div>
	<div><textarea name="sampleText" id="sampleText" rows="10" cols="50"></textarea></div>
	Characters Remaining: <strong><span id="remaining">140</span></strong>
</div>

 Description:

When the user starts typing inside the textarea, the keyup event gets fired and the script calculates the number of characters remaining by subtracting the user input from the total number of characters and display it.

Click Here to view the demo.

0 Comments

Leave a Comment.