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