Tuesday, 25 December 2012 13:54

how to limit the maximum number of characters in textbox control

Written by 
Rate this item
(0 votes)

limiting the number of characters in a textbox control
is tricky and useful.

the two functions in the codes mainly used to do that.
these two functions are-Limitvalidation and get_object.

the first function-Limitvalidation has three parameters-
one->the texbox object
two->Div id for holding the text
three->and the maximum number of characters the textbox control
can keep

the second function is used to guarantee that all
browsers are capable of access all from elements.

functions along with page codes shown below -

in the jscript.js file the following functions
written as follows -

function Limitvalidation(obj, divID, maxchar) {
objDiv = get_object(divID);
if (this.id) object = this;
var remainChar = maxchar - object.value.length;
if (objDiv){
objDiv.innerHTML = remaningChar + " charac: left";
}
if (remainChar <= 0) {
object.value = object.value.substring(maxchar, 0);
if(objDiv) {
objDiv.innerHTML = "zero characters left";}
return false;}
else{ return true; }}

function get_object(id) {
var obj= null;
if (document.layers) {
obj = document.layers[id];} else if (document.all) {
obj = document.all[id];
} else if (document.getElementById) {
obj = document.getElementById(id);}
return obj;}

main page codes follows -

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>limiting text box chars</title>
<script type="text/javascript" src="/js/Jscript.js" ></script>
</head>
<body>
<form id="form2" runat="server">
<div> <br />
<div id="labelMsg1">240 characters left</div>
<asp:TextBox ID="TextBox1" runat="server" Height="50px"
MaxLength="240"
TextMode="MultiLine" Width="600px" ToolTip="Summary:
(240 characters)"
onkeyup="return Limitvalidation(this, 'labelMsg1', 240)"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1" Display="Dynamic"
SetFocusOnError="True">*</asp:RequiredFieldValidator>
<br /><br />
<div id="labelMsg2">300 characters left</div>
<asp:TextBox ID="TextBox2" runat="server" Height="50px"
MaxLength="300"
TextMode="MultiLine" Width="600px" ToolTip="Summary:(300
characters)"
onkeyup="return Limitvalidation(this, 'labelMsg2', 300)"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
runat="server"
ControlToValidate="TextBox2" Display="Dynamic"
SetFocusOnError="True">*</asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button" runat="server" onclick="ButtonClick"
Text="Button" /><br /></div>
</form></body></html>

Read 3214 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.