tags:

views:

271

answers:

3

how can i make a character countdown like the one on twitter with jquery? and also limit the input to textarea.

+1  A: 

Using javascript and the onchange event.

See here: http://www.shiningstar.net/articles/articles/javascript/dynamictextareacounter.asp

Gazler
+3  A: 

I've used Aaron Russell's simply countable jQuery plugin with success; though, if I were to have written it, I would have designed it a bit differently (automatic counter div creation, using a data-maxlength attribute instead of a plugin option, etc).

Simple usage:

$('#my_textarea').simplyCountable();

Advanced usage:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});
Ryan McGeary
I think plugin is an overkill for it.
bodacydo
In jQuery, everything should be designed as a plugin, even if it's a "micro-plugin" (http://www.thegarvin.com/2009/10/28/clearer-code-with-jquery-micro-plugins.html).
Ryan McGeary
+2  A: 

Make a span and textarea and give them unique selectors (using an ID or class) like so:

<textarea class="message" rows="2" cols="30"></textarea>
<span class="countdown"></span>

And then make an update function like so:

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('.message').val().length;
    jQuery('.countdown').text(remaining + ' characters remaining.');
}

And make that function run when the page is loaded and whenever the message is changed:

jQuery(document).ready(function($) {
    updateCountdown();
    $('.message').change(updateCountdown);
    $('.message').keyup(updateCountdown);
});

Visit an example and view the source. jQuery makes things like this very simple.

Brian McKenna
+1, good usage of jsbin. it'd be nice if all examples used it.
cballou