Monday, December 8, 2014

How to Count Remaining Characters with Using jQuery

Here, You can take a look at a simple jQuery snippet which can count the total number of characters the user has entered in the textarea and it displays below the total no if remaining characters.  Many times, you have seen this type of stuff in micro blogging websites. For example, In the twitter, you may have seen this type of feature while creating a new tweet.

Count Remaining Characters with Using jQuery

Jquery Code :-

$(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 Code :-

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

How It Works :-

When anyone starts to type in the textarea, the keyup event gets fired, and the script calculates the total number of characters remaining by subtracting from the total number of characters and display it properly.

0 comments:

Post a Comment