Introduction:
In this article I am going to explain the code for counting and displaying the number of characters in a textbox or textarea using javascript.
Description:
My requirement is to count the characters in a textbox at runtime and restrict the number of characters. For that first i am creating a textbox.
In this article I am going to explain the code for counting and displaying the number of characters in a textbox or textarea using javascript.
Description:
My requirement is to count the characters in a textbox at runtime and restrict the number of characters. For that first i am creating a textbox.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<font size="1" face="arial, helvetica,
sans-serif">Only 50 characters allowed!
<input id="text" type="text" size="40" onkeydown="CountLeft(this.form.text,this.form.left,50);"
onkeyup="CountLeft(this.form.text,this.form.left,50);">
<input readonly type="lab" id="left" size="3" maxlength="3" value="50">
characters left</font>
</div>
</form>
</body>
</html>
In the above code i have created a html textbox and a label. While entering text in textbox the label show the number of characters. For counting the no of characters i have a javascript function "CountLeft" which is called on onkeydown and onkeyup events because we have to count the no of characters while entering the characters in the textbox and also while erasing the characters. Below is the javascript code.
<script type="text/javascript">
function CountLeft(field, count, max) {
// if
the length of the string in the input field is
greater than the max value, trim it
if (field.value.length > max)
field.value = field.value.substring(0, max);
else
//
calculate the remaining
characters
count.value = max - field.value.length;
}
</script>
Thus the above javascript function counts the number of characters in the textarea on both the onkeydown and onkeyup events. And if the count goes above 50 then it will restrict the characters.
Comments
Post a Comment