faqts : Computers : Programming : Languages : JavaScript : Forms : TextAreas/TextFields

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

103 of 127 people (81%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Can I restrict the numbers of character allowed to be inputted?
Can I script some maxLength for Textareas?

Mar 18th, 2000 11:47
Martin Honnen,


For 
  INPUT TYPE="text"
fields you can (and should) use the 
  MAXLENGTH
attribute to specify the maximum number of characters allowed, e.g.
  <INPUT TYPE="text" MAXLENGTH="20">
restricts the number of characters to 20.
With IE4+ and NN6 this attribute is scriptable as
  fieldRef.maxLength
and changeable e.g.
  <INPUT TYPE="text" NAME="aField" MAXLENGTH="5">
  <INPUT TYPE="button" VALUE="increase maxlength"
         ONCLICK="this.form.aField.maxLength = 
                    parseInt(this.form.aField.maxLength) + 2;
                  alert(this.form.aField.maxLength)"
  >
adjusts the maxLength.

For TEXTAREA elements no such attribute exists. Here you have to use 
onkeydown event handling to restrict the number of characters allowed.
The following contains a 
  checkMaxLength
handler (working for NN4 and IE4+) which gets passed a textarea 
element, an event object and the maxLength to check for.
It then allows for all control keys besides the return key (that could 
be improved) to be inputtted and for other keys the length of the 
textarea's value is checked before the key is allowed.
For IE some effort is taken to allow selecting and overwriting of text 
area content even when the maxLength is reached. For NN4 that is rather 
difficult as onselect doesn't work. So once your maxLength is reached 
with NN4 you can't simply select text and overwrite it unless you use 
backspace.

<HTML>
<HEAD>
<SCRIPT>
function checkMaxLength (textarea, evt, maxLength) {
  if (textarea.selected && evt.shiftKey) 
    // ignore shift click for select
    return true;
  var allowKey = false;
  if (textarea.selected && textarea.selectedLength > 0)
    allowKey = true;
  else {
    var keyCode = 
      document.layers ? evt.which : evt.keyCode;
    if (keyCode < 32 && keyCode != 13)
      allowKey = true;
    else           
      allowKey = textarea.value.length < maxLength;
  }
  textarea.selected = false;
  return allowKey;
}
function storeSelection (field) {
  if (document.all) {
    field.selected = true;
    field.selectedLength = 
      field.createTextRange ?
        document.selection.createRange().text.length : 1;
  }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
<TEXTAREA NAME="aTextArea" ROWS="2" COLS="10" WRAP="soft"
          ONKEYDOWN="return checkMaxLength(this, event, 20)"
          ONSELECT="storeSelection(this)"
></TEXTAREA>
</FORM>

</BODY>
</HTML>