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 badges4 Answers
Reset to default 3You 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..
}
});