Link to home
Start Free TrialLog in
Avatar of shlomof
shlomof

asked on

limit number of characters in <textarea>

Is there any way to limit number of character in <textarea> same as "maxlength" property in <input type="text" maxlength="50">?  I need something to work exectly same way - no warnings and no alerts.  Just prevent from additing more characters.
Avatar of dij8
dij8
Flag of New Zealand image

Not really.  You could write a script that runs on keypress.  It would have to check the length of the value of the text area and if it is longer than a specific limit it would then change the value to the first however many characters.

<script language="javascript" type="text/javascript">
  function settalength(field) {
    field.value = field.value.substr(0,50)
  }
</script>
<textarea onkeypress="settalength(this)"></textarea>

Doing it this way will have the last character change as a new key is pressed.  And note that hitting return is good for two characters (carriage return, line feed).
Here's a script that does limit the number of characters you can enter into a text box.  It's a little longer than dij8's, but you can see a working demo of it too.

http://www.shiningstar.net/articles/articles/javascript/dynamictextareacounter.asp?ID=AW
ASKER CERTIFIED SOLUTION
Avatar of dij8
dij8
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of shlomof
shlomof

ASKER

ClassyLinks,

This script is doing exactly the same as dij8's.  Thanks anyway.
Avatar of shlomof

ASKER

thanks dij8!!!
Glad to have helped.  Thanks for the A.

And Classylinks, thanks for the subtle tip on fixing the last character problem I had. :-)
Oh...is that what I did???  ;-)  LOL

Ciao for now!