2015-04-02 30 views
0

我已經成功做了一次字數使用以下JS文本區域:如何做一個字的使用jQuery多文字區域算什麼?

jQuery('span.after-amount').append(' - You have <span class="wordcount">0</span> words.'); 

    jQuery('textarea').on('input', function($) { 

     var regex = /\s+/gi; 
     var count = jQuery(this).val().trim().replace(regex, ' ').split(" ").length; 

     $('.wordcount').html(count); 


    }); 

我的HTML:

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea> 
<span class="after-amount">You have <span class="wordcount">0</span> words.</span> 

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea> 
<span class="after-amount">You have <span class="wordcount">0</span> words.</span> 

<textarea class="tmcp-field tmcp-textarea" name="tmcp_textarea_2"></textarea> 
<span class="after-amount">You have <span class="wordcount">0</span> words.</span> 

這裏是一個Fiddle

我需要字數爲每個文本區域,有一個簡單的方法來做到這一點沒有單獨選擇每個textarea的?

回答

1

這是我的解決方案,首先我將您的事件處理程序更改爲keyup,並使用$(this)開始計算每個textarea值的長度,以便獲取當前的textarea。

$(function(){ 
    $('textarea').on('keyup', function(){ 
     var wordsLength = $(this).val().length; 
     $(this).next().find('.wordcount').html(wordsLength); 
    }); 
}); 

檢查此updated jsfiddle。希望這有助於

+0

真棒的感謝!偉大的作品,只是長度改變$(本).VAL()爲$(本).VAL()。修剪()。斯普利特(」「)。長度爲字來代替的角色。 – 2015-04-02 01:19:08

+0

哎喲,我忘了補充一個。好的 – 2015-04-02 01:21:54

1

就發現.wordcount<li>

jQuery('textarea').on('input', function($) { 
     var regex = /\s+/gi; 
     var count = jQuery(this).val().trim().replace(regex, ' ').split(" ").length; 
     jQuery(this).parent().find('.wordcount').html(count); 
); 
+0

這個工作也謝謝! – 2015-04-02 01:22:54

相關問題