Satchel
Satchel

Reputation: 16724

How to show interactive character limits?

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?

Upvotes: 3

Views: 865

Answers (5)

devio
devio

Reputation: 37205

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);"

Upvotes: 5

SpliFF
SpliFF

Reputation: 38956

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: How to show interactive character limits?

Upvotes: 1

Aaron Watters
Aaron Watters

Reputation: 2846

You can also use simple javascript event handling to show character counts for input elements. No server side processing required.

This javascript catches the key-press event for a text area "txt" and shows the character count in a span "count".

See it running at http://aaron.oirt.rutgers.edu/myapp/root/charCount.html

<html>
<head>

<script>
function go() {
    var txt=document.getElementById("txt");
    txt.onkeydown = countTxt;
}
function countTxt() {
    var txt=document.getElementById("txt");
    var count=document.getElementById("count");
    count.innerHTML = txt.value.length+1; // count the character not shown yet ;)
}
</script>

</head>
<body onload="go()">

<h3>type in the text area and see the count change</h3>

<textarea id="txt" rows="8" cols="30"></textarea>
<br>
count: <span id="count"> 0</span>

</body>

The count can be off my +-1 -- fixing that (if you really want to) is left to the reader.

Upvotes: 0

Element
Element

Reputation: 4031

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);

Upvotes: 0

mmcdole
mmcdole

Reputation: 92805

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.

Upvotes: 12

Related Questions