最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Count words in real time - Stack Overflow

programmeradmin3浏览0评论

I am using the following jQuery functionality to count words in real time:

$("input[type='text']:not(:disabled)").each(function(){
            var input = '#' + this.id;
            word_count(input);

            $(this).keyup(function(){
                word_count(input);
            })

        });

var word_count = function(field) {
        var number = 0;
        var original_count = parseInt($('#finalcount').val());
        var matches = $(field).val().match(/\b/g);
        if(matches) {
            number = matches.length/2;
        }
        $('#finalcount').val(original_count + number)
    }

The issue I am running into is that when I start typing in an input field, the count increases immediately by two, even on spaces and my delete key. Any ideas why this would happen?

I was following this tutorial: /

Input: <input class="widest" id="page_browser_title" name="page[browser_title]" size="30" type="text" value="">

Display Input: <input class="widest" disabled="disabled" id="finalcount" name="page[word_count]" size="30" type="text" value="662">

I am using the following jQuery functionality to count words in real time:

$("input[type='text']:not(:disabled)").each(function(){
            var input = '#' + this.id;
            word_count(input);

            $(this).keyup(function(){
                word_count(input);
            })

        });

var word_count = function(field) {
        var number = 0;
        var original_count = parseInt($('#finalcount').val());
        var matches = $(field).val().match(/\b/g);
        if(matches) {
            number = matches.length/2;
        }
        $('#finalcount').val(original_count + number)
    }

The issue I am running into is that when I start typing in an input field, the count increases immediately by two, even on spaces and my delete key. Any ideas why this would happen?

I was following this tutorial: http://www.electrictoolbox.com/jquery-count-words-textarea-input/

Input: <input class="widest" id="page_browser_title" name="page[browser_title]" size="30" type="text" value="">

Display Input: <input class="widest" disabled="disabled" id="finalcount" name="page[word_count]" size="30" type="text" value="662">

Share Improve this question edited Sep 14, 2011 at 20:13 Jose Faeti 12.3k6 gold badges39 silver badges53 bronze badges asked Sep 14, 2011 at 19:53 dennismonsewiczdennismonsewicz 25.5k35 gold badges117 silver badges194 bronze badges 5
  • Can you enter your html also for the input and display div? – willdanceforfun Commented Sep 14, 2011 at 19:57
  • 1 Do you have a jsfiddle ? – Jonathan Allard Commented Sep 14, 2011 at 19:59
  • Here is a link to jsfiddle... jsfiddle.net/M7Jny – dennismonsewicz Commented Sep 14, 2011 at 20:04
  • The fiddle is not running for me - i get undefined is not a function in the console. Anyone see it working? – Adam Hopkinson Commented Sep 14, 2011 at 20:05
  • 1 @adam You have to move the word_count declaration above the each call. – Dennis Commented Sep 14, 2011 at 20:11
Add a comment  | 

2 Answers 2

Reset to default 14

It is incrementing with every key press because you are telling it to with:

$('#finalcount').val(original_count + number)

And if you add another word, you will find that it increments not by 2, but by 3. Presumably, you have several inputs on the page, and you intend for the finalcount input to display the number of words in each input. Either store the counts in a variable and add the variables together to get your finalcount value. Or count the words in each input every time.

var wordCounts = {};

function word_count (field) {
    var number = 0;
    var matches = $(field).val().match(/\b/g);
    if (matches) {
        number = matches.length / 2;
    }
    wordCounts[field] = number;
    var finalCount = 0;
    $.each(wordCounts, function(k, v) {
        finalCount += v;
    });
    $('#finalcount').val(finalCount)
}

Working demo: http://jsfiddle.net/gilly3/YJVPZ/

Edit: By the way, you've got some opportunities to simplify your code a bit by removing some redundancy. You can replace all of the JavaScript you posted with this:

var wordCounts = {};
$("input[type='text']:not(:disabled)").keyup(function() {
    var matches = this.value.match(/\b/g);
    wordCounts[this.id] = matches ? matches.length / 2 : 0;
    var finalCount = 0;
    $.each(wordCounts, function(k, v) {
        finalCount += v;
    });
    $('#finalcount').val(finalCount)
}).keyup();

http://jsfiddle.net/gilly3/YJVPZ/1/

Edit

Check this example.


Why don't you use split(" ") instead of matching and dividing the result? You will have an array containing all your words, the length of the array will be the number of words.

var matches = $(field).val().split(" ");

Also, why are you adding every time the matches to the old result?

$('#finalcount').val(original_count + number)

Isn't this adding every time all the words twice?

发布评论

评论列表(0)

  1. 暂无评论