Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  123] [ 2]  / answers: 1 / hits: 69840  / 11 Years ago, sun, july 28, 2013, 12:00:00

I managed to make this little jquery function to count the number of words entered in textarea field.



here is the fiddle



and here is the code:



JQUERY:



$(document).ready(function()
{
var wordCounts = {};
$(#word_count).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;
});
$('#display_count').html(finalCount);
am_cal(finalCount);
}).keyup();
});


and here is html code



<textarea name=txtScript id=word_count cols=1 rows=1></textarea>
Total word Count : <span id=display_count>0</span> words.


how can i make modifications in it to have the output like this



Total word Count : 0 words. Words left : 200



and when it reach 200 words it shall not allow to either paste, or type more words in the textarea field, in jquery? i.e. it shall restrict user to type exactly 200 words not more than that.



Please help.



Thanks a lot in advance.



EDIT: The modification is needed in this code only, as i am very well aware of the plugins, but they may interfere with the main code.


More From » jquery

 Answers
26

Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.


You will need to programmatically edit the value of the textarea you have as #wordcount:


$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;

if ((this.value.match(/S+/g)) != null) {
words = this.value.match(/S+/g).length;
}

if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});

http://jsfiddle.net/k8y50bgd/


[#76688] Friday, July 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 4 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;