views:

787

answers:

4

I'm modding some jquery code to limit the word count of a textfield but I can't figure out how to get the value. Here's 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>

Specifically, what should "$wordCount" be equal to to return the current value?

I think it should be easy, but I can't seem to figure it out.

Any ideas?

Thanks, Scott

A: 

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

var $wordCount = $('#count').html();
John Fisher
+1  A: 

If I've understood you correctly, you need to put the code to get the value inside an event handler for the input/textarea, for example in an event handler foe the keypress event. This way you can restrict the number of words whilst the user is entering text into the input/textarea.

Russ Cam
I can't mark both your answer and cballou answer correct but thanks for point this out for me. Basically, I needed to create an event handler to define the wordcount variable - cballou's answer has an example.Makes perfect since. Thanks Russ Cam!
Scott
No problem, happy to help :)
Russ Cam
+1  A: 

I don't quite understand the $wordCount variable. I believe you may be trying to do the following:

$("#edit-field-message-0-value").keyup(function() {
    $this = $(this);
    var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;

    if (wordcount > $limitWords) {
        $this.addClass('error');
    } else {
        $this.addClass('not-error');
    } 
});

I am also going to presume you wanted to store the current count:

$("#edit-field-message-0-value").keyup(function() {
    $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');
    } 
});
cballou
I can't mark both your answer and Russ Cam's answer but thanks for point this out for me. Basically, I needed to create an event handler to define the wordcount variable.
Scott
A: 

I wrote a bad ass plugin that you may enjoy: jQuery word and character counter plugin

qwertypants