I am using a a textarea field in a form that is made on html and the processing is done by php. I want to limit the number of characters the user can enter in the textarea. Is there any way by which this can be done because the textarea field is then stored into a mysql database and thus i have to limit the user data according to the varchar value of the field.
Any help?
This is a very easy way to limit the length of a text area via JavaScript.
text area field:
JavaScript function:
When the user types past 40 characters it just removes them.
You can limit this by setting
maxlength
attribute on textarea tag like<textarea maxlength="120"></textarea>
in HTML and additionally "cut" input string in PHP bysubstr()
function.As mentioned by s.webbandit you can use
maxlength
, but note that this is a new feature introduced in HTML5, as W3 Schools article about<textarea>
, so "bulletproof" solution needs Javascript. Somaxlength
is not supported in Internet Explorer until version 10 and in Opera not at all.Here is one approach that uses Javascript to help you out:
You can then use it like this (original source):
This should get you going.
I've tried a lot of different ways to limit text in textareas, and the best I have found (client side) is with the jQuery.Maxlength.js plugin. Simple quick and covers them all!
Step 1. Include Maxlength plugin script
Step 2. Add maxlength attribute to
Step 3. Initialize plugin
https://github.com/viralpatel/jquery.maxlength