Instant Character Counter Using jQuery

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″ )

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<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>

About prasad k

Prasad Kuppusamy has written 76 post in this blog.

i m php developer, web designer.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>