Thursday, 6 August 2015

Show remaining characters to be entered in textarea using jQuery

Leave a Comment

Some websites like Twitter limit number of characters that are typed in textarea. We can also see the remaining number of characters left for typing. This kind of feature can be easily implemented using jQuery.

Create a textarea  with id, cols, rows and maxlength attributes. In this example we will limit number of character to 25. Create a span with id. This span tag shows the number of characters remaining in textarea.

<textarea id="textarea" cols="20" rows="5" maxlength="25"></textarea>
Remaining Characters <span id="remain">25</span>

Now the jQuery part, here we should use .keyup event trigger in jQuery to capture every key release by the user in textarea. Create a new variable max, this is the maximum number of characters we can enter in the textarea. Now use if condition to check the characters entered in the textarea is less than or equal to 25 ie max variable. If condition is true, then subtract the number of characters in the textarea from max. Finally display that value in span tag. Thats it.

$("#textarea").keyup(function(){
var max = 25;
if($(this).val().length <= max)
var let = max - $(this).val().length;
$("#remain").text(let);
});

Lets see the full code

<textarea id="textarea" cols="20" rows="5" maxlength="25"></textarea>
Remaining Characters <span id="remain">25</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("#textarea").keyup(function(){
var max = 25;
if($(this).val().length <= max)
var let = max - $(this).val().length;
$("#remain").text(let);
});
</script>

0 comments:

Post a Comment

.