I normally work in asp.net so use asp:TextBoxes frequently to capture data input to a database. With the best intentions I guess how many characters the user will need to enter and make the field in the database able to hold that many characters. I may also be limited by the spacing on the form. Especially in “Notes” text boxes a user then wants to enter a life story! The TextBox lets them type what they want but the database doesn’t store it all and when they read the record they find their typing has been cut off.
This jQuery script helps by not letting them type (or paste) too much.
- At the top of your page (in the head section perhaps), if you haven’t already got a link to jQuery, add one.
- Add a link to the MaxLength script.
- Add javascript functions for each TextBox you want to affect.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-3.4.1.min.js"></script>
<script src="Scripts/MaxLength.min.js"></script>
<script type="text/javascript">
$(function () {
//Specifying the Character Count control explicitly
$("[id*=TextBox1]").MaxLength(
{
MaxLength: 50,
CharacterCountControl: $('#counter')
});
//Disable Character Count
$("[id*=TextBox2]").MaxLength(
{
MaxLength: 20,
DisplayCharacterCount: false
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="TextBox1">Text Box 1:</label>
<asp:TextBox ID="TextBox1" runat="server"
Height="85px" TextMode="MultiLine"
Width="260px">
</asp:TextBox>
<br />
<br />
<label for="TextBox2">Text Box 2:</label>
<asp:TextBox ID="TextBox2" runat="server"
Height="85px" TextMode="MultiLine"
Width="260px">
</asp:TextBox>
</div>
</form>
</body>
</html>
TextBox1 has 20 characters in it. It has a maximum of 50 characters allowed and the remaining characters is displayed.
TextBox2 has 20 characters in it and no more typing is possible as the maximum is 20 characters. The remaining characters display is off for this TextBox.
MaxLength.js is available from https://gist.github.com/lscott3/3835702
I found this at https://www.jqueryscript.net/form/Max-Length-Text-Fields-jQuery.html