Introduction:When we are taking input from a user it is essential that the length of the user's input does not exceed the size of the corresponding database table field; for example if we defined a table field with the name comments of type varchar(50) and the user is entering a comments into a TextBox then if the user enters more than 50 characters then when we are trying to insert the data into the comment field it will throw an exception. Or if we are trying to make a SMS application and we want to restrict the user up to 160 character than it is necessary to inform the user that he is exceeding the SMS limit. In this article we'll look at creation of a JavaScript function for counting a character from a Textbox and showing how many characters remain.This article provides a few steps that will be easy to follow.Step 1:First, we need to add a small JavaScript function in your form's Body or Head tag.<script type="text/javascript">
function textCounter(field, countfield, maxlimit){
if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);else countfield.value = maxlimit - field.value.length;}</script>Step 2:Now call this function in the TextBox's OnKeyUp and OnKeyDown events. And pass parameters to this function as in:<asp:TextBox ID="txtMessage" TextMode="MultiLine" Width="200px" Rows="3" runat="server" onkeyup="textCounter(txtMessage, this.form.remLen, 160);" onkeydown="textCounter(txtMessage, this.form.remLen, 160);" />You can change the maxlimit character by passing the maxlimit parameter.Step 3:Now add another TextBox for showing how many characters are left.<input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" /> characters leftStep 4:Run Your Website.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: