songzog.com

Word Counter : Show left word and throw exception when exceed the maximum limit in the text field using Jquery

Views: 180 Comment: 0 Category: Programming Language JavaScript Updated: Jun 23, 2015 12:37PM

on keypress, need to show  left words from maximum word limit.

Here is the Jquery class which return left of the world when you enter word in the text/textarea  field

<script type="text/javascript">
    jQuery.fn.wordCount = function(params, max){
        var obj = {
            counterElement:params
        };
        var total_words;
        var left_words;
        if(params) {
            jQuery.extend(obj, params);
        }
        jQuery('#'+obj.counterElement).html( 'Maximum word limit <strong>'+max+'</strong>');
        //for each keypress function on text areas
        this.keypress(function()
        {
            total_words=this.value.split(/[\s\.\?]+/).length;
            left_words = max- total_words;
            if(total_words <= max) {
                jQuery('#'+obj.counterElement).html( '<strong>'+left_words+'</strong> words left.   Maximum word limit <strong>'+max+'</strong>');
            }
            else return false;
        });
    };
</script>

Using :
<textarea id="keywords" rows="6" cols="30" name="keywords">Test without Abstgract</textarea>
<span id="keywordsCounter"></span>

<script language="JavaScript">
    $(document).ready(function()
    {
        $('#keywords').wordCount('keywordsCounter', 300);
        
    });
</script>



 

Recent Post

Category

ads