Instant Character Counter Using jQuery

By | August 11, 2012

Instant character counter using jquery in the sense without refreshing the page, we have to count the number of character left or number of character typed. Only option to count the typed character is by using client side language ( jQuery or javascript).

Here is the jQuery code to count the text.

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js”>
</script> – jQuery library will be loaded from google site

$(“#val1”).keyup  ID of text box is val1. keyup event is used to find any character is typed or deleted in text box with ID value val1

var length1=$(“#val1”).val().length;  –  Text length of text box will be stored in a variable length1.

var length2=10-length1; – We have to display character left. By subtracting length1 from 10 , we can get character left value.

$(“#dis”).html(length2);  – Character left will be displayed in label with ID dis.

A problem will rise when more than 10 character is typed. So we have to fix the maximum length of text box as 10. ( maxlength=”10″ )

 

[code type=html]

<html>
<head>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js”>
</script>
<script type=”text/javascript”>
$(document).ready(function(){
$(“#val1”).keyup(function(){
var length1=$(“#val1”).val().length;
var length2=10-length1;
$(“#dis”).html(length2);
});
});
</script>
</head>
<body>
<form>
<strong>Maximum Length of username is 10</strong> <br>
<br>
Name<input type=”text” name=”val” id=”val1″ size=”10″ maxlength=”10″><br>
</form>
Character Left: <label id=”dis”>10</label>
</body>
</html>

[/code]

Leave a Reply

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

sprang-bangalay