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

javascript - jQuery textarea word count on form submit - Stack Overflow

programmeradmin0浏览0评论

I have been looking around for a function that counts the number of words in a textarea when I click the form submit button.

I am trying to display a message to the user that if they click submit and have only entered 50 or less words. This will be a confirm message basically saying "You have entered less than 50 words, are you sure you would like to continue?"...or something.

Cheers

I have been looking around for a function that counts the number of words in a textarea when I click the form submit button.

I am trying to display a message to the user that if they click submit and have only entered 50 or less words. This will be a confirm message basically saying "You have entered less than 50 words, are you sure you would like to continue?"...or something.

Cheers

Share Improve this question edited Dec 19, 2012 at 1:51 vivek 2,0041 gold badge18 silver badges26 bronze badges asked Dec 19, 2012 at 1:23 puks1978puks1978 3,69712 gold badges47 silver badges108 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

You should use split method using a space as a splitter, and then you take the length of the array.

var wordCount = $('textarea').val().split(' ').length

HTML:

<form id="confirmForm">
    <textarea id="moreThan50"></textarea>
    <button type="submit">Submit</button>
</form>​

JS:

$('#confirmForm').submit(function(ev){
    var wordCount = $('#moreThan50').val().split(/\s/g).length;

    if (wordCount < 50) {
        if (!confirm('Less than 50 words, are you sure you want to submit?')) {
            ev.preventDefault();
        }
    }
});​

See demo

Another method, you can use regex and count 'words' using \b:

var words = $('#textareaid').val().match(/\b(\w+)\b)/g).length;

Ninja-Edit Oops, should have been .val not .text

You can split at word boundaries using regular expressions..

$('form').submit(function(){
   var words = $('textarea', this).val().split(/\b\W/);
   if (words.length < 50){
     // propmpt here.. and allow or cancel the submit..
   }
});
发布评论

评论列表(0)

  1. 暂无评论