Uncategorized

Simple Javascript Word Counter Using Jquery

The script below prevents a text field from accepting more than 200 words.

<script type='text/javascript'>
 
    //adds word counter
    $('.max200').each(function(){
        $(this).parent().append('<p style="font-weight:bold">200 words remaining</p>');
    });
 
    // counts as you type
    $('.max200').keydown(function(){
        checkLength($(this));
    });
 
    //count after pasted
    $('.max200').change(function(){
        checkLength($(this));
    });
 
    function checkLength(element){
        str=$(element).val();
        str_array=str.split(/\W+/);
        s=str_array.length;
        l=200-s;
        if(l<0){
 
            //$(this).parent().find('.words_left').css('color','red');
            shortened=str_array.slice(0,200);
            shortened_str=shortened.join(' ');
 
            $(element).val(shortened_str+ ' ');
            l=0;
        }
 
        $(element).parent().find('.words_left').text(l +' words remaining');
    }
 
</script>

To apply it the textarea  needs to be in its own  wrapper and have the class “max200” see below:

 

<ul>
 
 <li>
 
<label for='message'>Message</label>
 
<textarea name='message' class='max200'></textarea>
 
</li>
 
</ul>

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.