Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1047 How do you limit the length (in characters) of text entered in a textarea form field?

irt.org | Knowledge Base | JavaScript | Form 5 | Q1047 [ previous next ]

Q1047 How do you limit the length (in characters) of text entered in a textarea form field?

This can't be done whilst the user is entering data into the textarea - only after they have finished:

<script language="JavaScript"><!--
function validate(what) {
    if (what.length > 10) {
        alert('Must be less than 10 characters');
        return false;
    }
    return true;
}
//--></script>

<form name="formName" onSubmit="return validate(documents.formName.textName.value)">
<textarea name="textName" onChange="validate(this.value)"></textarea>
</form>

This isn't true any more for all browsers. You can use onkeypress or onKeyUp for "realtime" checks. It doesn't work on older browsers, so it's best used in addition to a check like the one above:

<textarea onKeyUp="if (this.value.length>30) { alert('Please enter only 30 chars'); this.value=this.value.substring(0,30) }"></textarea>

Feedback on 'Q1047 How do you limit the length (in characters) of text entered in a textarea form field?'


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.