views:

1643

answers:

7

An HTML text input has an attribute called "maxlength", implemented by browsers, which if set blocks user input after a certain number of characters.

An HTML textarea element, on the other hand, does not have this attribute. My goal is to emulate the behavior of maxlength on an HTML textarea. Requirements:

  • At a minimum, show (CSS change) that the user typed in too many characters.
  • Ideally, block the user from typing more characters, as happens on an HTML input.

It is understood that server-side validation should check the length again. Here I am focusing on the client-side part only.

My question is: what is the cleanest client-side way of emulating maxlength on an HTML textarea? Ideally, point to a proven, open source, piece of JavaScript that you have used.

+10  A: 

Look at the comments on this site, with a count down. I have done it like this before, and it is simple and effective. SO makes good use of color too.

Perhaps you don't have enough rep to see the comment box.

It runs a little countdown while you type. At it approaches a threshold, the color changes from yellow to red. All using javascript and I assume the keyup event of the textarea.

EDIT: How about having it done w/jquery?

<script language="javascript" type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready( function () {
    setMaxLength(); 
    $("textarea.checkMax").bind("click mouseover keyup change", function(){checkMaxLength(this.id); } )
});
function setMaxLength() {
    $("textarea.checkMax").each(function(i){
     intMax = $(this).attr("maxlength");
     $(this).after("<div><span id='"+this.id+"Counter'>"+intMax+"</span> remaining</div>");
     });
    }
function checkMaxLength(strID){
     intCount = $("#"+strID).val().length;
     intMax = $("#"+strID).attr("maxlength");
     strID = "#"+strID+"Counter";
     $(strID).text(parseInt(intMax) - parseInt(intCount));
     if (intCount < (intMax * .8)) {$(strID).css("color", "#006600"); } //good
     if (intCount > (intMax * .8)) { $(strID).css("color", "#FF9933"); } //warning at 80%
     if (intCount > (intMax)) { $(strID).text(0).css("color", "#990000"); } //over
    }
</script>

And the HTML is

<textarea id="text" maxlength="250" class="checkMax"></textarea>
MrChrister
A: 

Here is Javascript that works ok for me:

onBlur="if (this.value.length > 500) { alert('The notes field only allows 500 characters. You have ' + this.value.length + ' characters.'); this.focus(); return false; }"
sjbotha
A: 

I think the following is as "clean" as it gets. Make an event handler in Javascript that takes the keydown event and the textarea field as input. Check the length of the text in the field in this handler and return false if the maxlength is reached. (Of course make any css style switching before returning). Return true otherwise. The textarea should look like this.

<textarea onkeydown="return checkMaxLength(event, this, 1000);"></textarea>
PEZ
+6  A: 

PPK's Textarea Maxlength script is available on his site. Nothing fancy, just plain old JavaScript.

You can easily use this as a starting point and make changes to accommodate your CSS "notification" requirement.

Note that the author states: "The purpose of my script is not to enforce the maximum length, though it can easily be changed to do that. However, I decided to restrict my script to giving a polite reminder when the user exceeds the maximum amount of characters."

Zack Mulgrew
A: 

Use a javascript framework (prototype, jquery, etc) so that you have cross-browser event support. write a one liner on keyup to prevent the user from entering the maxlength.

note: You'll also have to check this length server side.

j4y
+2  A: 

I found a nice script here that stops the user from entering more text after the length of the input string exceeds the MaxLen parameter, it has the undeniable benefit of mostly staying out of the user's face.

My problem with that script was that it also blocked the navigation keys(arrows, home, end) along with backspace and delete, so I modified it slightly, otherwise the user couldn't delete the text he entered if he reached the limit set by MaxLen (which would be kind of hilarious :P).

Javascript:

function imposeMaxLength(Event, Object, MaxLen)
{
     return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}

And the HTML that goes with it:

<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">

The user can still get around this limitation by pasting text into the textarea, but that can be easily solved inside imposeMaxLength.

gzzzur
Is it possible to elaborate a bit more on how pasting can be overcome?As far as I know onkeypress will not fire when a user does a right-click to paste text.
Ben