jQuery: Count words in real time

后端 未结 2 1001
抹茶落季
抹茶落季 2020-12-03 22:37

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

$(\"input[type=\'text\']:not(:disabled)\").each(function(){
            var input          


        
2条回答
  •  余生分开走
    2020-12-03 22:51

    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/

提交回复
热议问题