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

I have been looking around for a function that counts the number of words in a textarea when I click th

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..
   }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745379716a4625167.html

相关推荐

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

    I have been looking around for a function that counts the number of words in a textarea when I click th

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信