ashis
ashis

Reputation: 381

word counting Jquery function

here is the script for counting words.

  1. Can it be made simple?
  2. on deleting all or partial of the words it does not update the values. i tried but could not come up with anything. How can it be done?
  3. "Can it be made simple?" This shall be counted as FIVE words. But check this [without quotes] this script copunts it SIX. What is wrong?

HTML Message: Total word Count : 0 words.

jquery

$(document).ready(function () {
    $('#word_count').wordCount();
});

jQuery.fn.wordCount = function (params) {
    var p = {
        counterElement: "display_count"
    };
    var total_words;

    if (params) {
        jQuery.extend(p, params);
    }

    //for each keypress function on text areas
    this.keypress(function () {
        total_words = this.value.split(/[\s\.\?]+/).length;
        jQuery('#' + p.counterElement).html(total_words);
    });
};

fiddle http://jsfiddle.net/ZmbxS/

Upvotes: 1

Views: 317

Answers (3)

adeneo
adeneo

Reputation: 318182

Can it be made simple?

sure can, use a word boundary matching anything that isn't whitespace :

$('#word_count').on('keyup', function() {
    $('#display_count').text(this.value.split(/\b\S+\b/g).length-1)
});

FIDDLE

and it seems like a wasted use of a plugin for something that can be done that easily ?

Upvotes: 6

mishik
mishik

Reputation: 10003

See this:

Demo

  1. You need to "trim" your value to ensure that there are no leading/trailing spaces (which produce mentioned +1)

  2. I've attached this handler to keyup event instead.

Code:

this.keyup(function () {
    my_value = this.value.replace(/^\s+|\s+$/, '');
    total_words = my_value.split(/[\s\.\?]+/).length;
    jQuery('#' + p.counterElement).html(total_words);
});

Upvotes: 0

Omar
Omar

Reputation: 699

I think it is a matter on the event you're using. I'd suggest you to bind the function to the change event.

For the regexp, it is not enough to make the split just by?:

stringValue.split(/\s/);

Best regards.

Upvotes: -1

Related Questions