Instant Character Counter Using jQuery


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

 

<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>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s