learn learn - 4 months ago 11
Javascript Question

Character limit countdown for multiple textareas on the same page?

At the moment I am trying to create essentially the same type of countdown on twitter textareas. It does work for the first textarea but it then duplicates the same amount of characters remaining for all posts when I start typing in the first texarea.

What I need to know is how do I get the characters remaining for only the current textarea?

HTML:

<textarea name="comment" class="inputField newComment">@'.$post['username']." ".'</textarea>
<span class="countdown"></span>


jQuery:

function updateCountdown() {

var remaining = 140 - $('.newComment').val().length;
$('.countdown').text(remaining + ' characters remaining');

if(remaining < 0){

$(this).siblings('.postComment').hide(500);

}else{

$(this).siblings('.postComment').show(500);
if(remaining <= 10){
$(this).siblings('.countdown').css("color","red");
}else{
$(this).siblings('.countdown').css("color","black");
}
}
}

$('.newComment').change(updateCountdown);
$('.newComment').keyup(updateCountdown);

Answer

Try something like this,

HTML

    <textarea name="comment" class="inputField newComment" data-limit=20></textarea>
<span class="countdown"></span>
<textarea name="comment" class="inputField newComment" data-limit=20></textarea>
<span class="countdown"></span>

JS

    $(document).ready(function () {
    $('textarea').on("propertychange keyup input paste",

    function () {
        var limit = $(this).data("limit");
        var remainingChars = limit - $(this).val().length;
        if (remainingChars <= 0) {
            $(this).val($(this).val().substring(0, limit));
        }
        $(this).next('span').text(remainingChars<=0?0:remainingChars);
    });
});

http://jsfiddle.net/qMbdW/3/

Comments