Limit the number of text field words in jQuery

I am modifying some jquery code to limit the number of words in a text field, but I cannot figure out how to get the value. Here is the code:

<script> var $limitWords = 20; var $wordCount = $('#count').val(); $(document).ready(function(){ $("#edit-field-message-0-value").keyup(function() { $('#count').html($('#edit-field-message-0-value').val().split(/\b[\s,\.-:;]*/).length); if ($wordCount > $limitWords) { $('#edit-field-message-0-value').addClass('error'); } else { $('#edit-field-message-0-value').addClass('not-error'); } }); }); </script> 

In particular, what should be the "$ wordCount" equal to returning the current value?

I think it should be easy, but I cannot figure it out.

Any ideas?

Thanks Scott

+1
source share
5 answers

I do not quite understand the $ wordCount variable. I believe you can do the following:

 $("#edit-field-message-0-value").keyup(function() { var $this = $(this); var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length; if (wordcount > $limitWords) { $this.addClass('error'); } else { $this.addClass('not-error'); } }); 

I also assume that you want to keep the current counter:

 $("#edit-field-message-0-value").keyup(function() { var $this = $(this); var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length; if (wordcount > $limitWords) { $('#count').html($limitWords); $this.addClass('error'); } else { $('#count').html(wordcount); $this.addClass('not-error'); } }); 
+2
source

The following script will not allow you to enter more limitWord :

 var limitWord = 20; var maxchars = 0; $("#edit-field-message-0-value").keyup(function() { $this = $(this); var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length - 1; if (wordcount < limitWord) { chars = $this.val().length; } else{ var text = $(this).val(); var new_text = text.substr(0,chars); $(this).val(new_text); } }); 
+2
source

It just expanded above, a great response from Pritham, I found that he was behaving rather strangely and changed

var wordcount = $this.val().split(/\b[\s,.-:;]*/).length - 1;

To:

var wordcount = jQuery.trim($this.val()).split(/\b[\s,.-:;]*/).length;

This sorts the behavior of a fancy wordcount (if you return the value back to the user for feedback)

+2
source

If you understand correctly, you need to put the code to get the value inside the event handler for input / textarea, for example, in the event handler that triggers the keypress event. Thus, you can limit the number of words while the user enters text in the input / text area.

+1
source

Since we don’t know what the "#count" element is, I took a queue from a method that sets a value using html (...). So this should work:

 var $wordCount = $('#count').html(); 
0
source

All Articles