Question

I have a text area where I do a countdown on .keyup() but it although it does what it supposed to it lets the user to believe that there id 1 character left to type, yet the length of the text area has reached the limit. Here is my code:

<script>
     var w_limit = 3000;
     $(document).ready(function(){
         $('#comment').keyup(function(e) {
            el = $(this);
            if(el.val().length >= w_limit){
                el.val( el.val().substr(0, w_limit) );
            } else {                    
                $("#word-count").text(w_limit-el.val().length + ' characters left');
            }
        });
     });
</script>
Was it helpful?

Solution

Aside from your typos, you need to always run the $("#word-count").text(stuff); part. Here's it working without the else:

var w_limit = 20;
$(document).ready(function () {
    $('#comment').keyup(function (e) {
        var el = $(this),
            val = el.val();
        if (val.length >= w_limit){
            el.val( val.substr(0, w_limit) );
        }
        $("#word-count").text(w_limit - el.val().length + ' characters left');
    });
});

DEMO: http://jsfiddle.net/eHstm/

(of course, I used a lower w_limit number for testing purposes)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top