views:

341

answers:

5

How does Stack Overflow show interactive character limits? Like when editing comments, it shows you how many characters you have left, as well as warning if it is too few.

I'd like that exact functionality in my Ruby on Rails... But not sure how to do it?

+13  A: 

Stackoverflow uses the jQuery JavaScript Framework and it has a lot of existing scripts and plugins for this sort of thing.

One example is this Interactive Character Limit for TextArea in jQuery demonstrated here.

I'm sure there are others as well.

Simucal
Nice demo. +1 .
Chathuranga Chandrasekara
I've been trying to get the TextArea without the Jquery to work...challenges with it....
Angela
@Angela, is there a reason you don't want to use jQuery? It helps solve browser compatibility issues.
Simucal
@Angela, if you insist on ~not~ using a javascript framework, then I suggest asking a new question asking how to do it in raw javascript.
Simucal
A: 

I think you are looking for some javascript, basically you add a handler to the textbox onkeypress event then to get the current length:

mytextbox.value.length

and to limit it you could do something like:

if (mytextbox.value.length > maxlimit) 
mytextbox.value = mytextbox.value.substring(0, maxlimit);
Element
A: 
Aaron Watters
+1  A: 

by using the onkeydown event on the input. There are millions of examples out there and frankly I'd be surprised if this isn't a duplicate question.

It is: http://stackoverflow.com/questions/823575/how-does-stack-overflow-show-interactive-character-limits

SpliFF
You linked to the same question! It is a duplicate of ... itself?
thornomad
+4  A: 

I use the following JavaScript function to restrict max length in textareas

function checkLength(edit, maxlen) 
{
if (edit.value.length > maxlen) 
 edit.value = edit.value.substring(0, maxlen);

    document.getElementById('remaining').innerHTML = edit.value.length;
}

Link this to your textarea's onKeyDown and onKeyUp attributes:

onKeyDown = "checkLength(this, 100);"
devio