How can I set the maxlength
in a textarea
? And why maxlength
is not working properly in textarea
?
There is no native max-length attribute for textareas.
The maxlength attribute defines the maximum number of characters (as UTF-16 code units) the user can enter into an <input> or <textarea> . This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the input or textarea has no maximum length.
The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element. Attribute Value: number: It contains single value number which allows the maximum number of character in Textarea element. Its default value is 524288.
Before HTML5, we have an easy but workable way: Firstly set an maxlength attribute in the textarea element:
<textarea maxlength='250' name=''></textarea>
Then use JavaScript to limit user input:
$(function() { $("textarea[maxlength]").bind('input propertychange', function() { var maxLength = $(this).attr('maxlength'); if ($(this).val().length > maxLength) { $(this).val($(this).val().substring(0, maxLength)); } }) });
Make sure the bind both "input" and "propertychange" events to make it work on various browsers such as Firefox/Safari and IE.
If you are using HTML 5, you need to specify that in your DOCTYPE
declaration.
For a valid HTML 5 document, it should start with:
<!DOCTYPE html>
Before HTML 5, the textarea
element did not have a maxlength
attribute.
You can see this in the DTD/spec:
<!ELEMENT TEXTAREA - - (#PCDATA) -- multi-line text field --> <!ATTLIST TEXTAREA %attrs; -- %coreattrs, %i18n, %events -- name CDATA #IMPLIED rows NUMBER #REQUIRED cols NUMBER #REQUIRED disabled (disabled) #IMPLIED -- unavailable in this context -- readonly (readonly) #IMPLIED tabindex NUMBER #IMPLIED -- position in tabbing order -- accesskey %Character; #IMPLIED -- accessibility key character -- onfocus %Script; #IMPLIED -- the element got the focus -- onblur %Script; #IMPLIED -- the element lost the focus -- onselect %Script; #IMPLIED -- some text was selected -- onchange %Script; #IMPLIED -- the element value was changed -- %reserved; -- reserved for possible future use -- >
In order to limit the number of characters typed into a textarea
, you will need to use javascript with the onChange
event. You can then count the number of characters and disallow further typing.
Here is an in-depth discussion on text input and how to use server and client side scripting to limit the size.
Here is another sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With