title: jquery word count and mvc csharp
body: <p>I am coding in c# MVC4.</p>
  
  <p>In my create.cshtml</p>
  
  <p>I have this code:</p>
  
  <pre><code>@{
      ViewBag.Title = "My wonderful creation";
  }
  &lt;script type="text/javascript"&gt;
  $(document).ready(function() {
    $("#word_count").on('keyup', function() {
      var words = this.value.match(/\S+/g).length;
      if (words &gt; 100) 
      {
        var trimmed = $(this).val().split(/\s+/, 100).join(" ");
        $(this).val(trimmed + " ");
      }    
    });
  }); 
  &lt;/script&gt;
  
  
   &lt;div class="editor-field"&gt;
              @Html.TextAreaFor(model =&gt; model.mywonderful, new { @id = "word_count" })
              @Html.ValidationMessageFor(model =&gt; model.mywonderful)
          &lt;/div&gt;
  </code></pre>
  
  <p>this doesn't work. when i view source, the code looks like this:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  $(document).ready(function() {
    $("#word_count").on('keyup', function() {
      var words = this.value.match(/\S+/g).length;
      if (words &gt; 100) 
      {
        var trimmed = $(this).val().split(/\s+/, 100).join(" ");
        $(this).val(trimmed + " ");
      }    
    });
  }); 
  &lt;/script&gt;
  
  
  &lt;div class="editor-field"&gt;
              &lt;textarea  id="word_count" name="mywonderful" rows="2" cols="20"&gt;
  &lt;/textarea&gt;
              &lt;span class="field-validation-valid" data-valmsg-for="mywonderful" data-valmsg-replace="true"&gt;&lt;/span&gt;
          &lt;/div&gt;
  &lt;script src="/Scripts/jquery-1.9.1.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>How do I get the word count and validation to work in c# mvc. This is very easy to do in php however, c# mvc is a different story.</p>
  
  <p>I ended up using plain old javascript so that i can use the same code for several textareas:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      var maxWords = 100;
      function limitLengthInWords(field)
      {
          var value = field.value,
              wordCount = value.split(/\S+/).length - 1,
              re = new RegExp("^\\s*\\S+(?:\\s+\\S+){0," + (maxWords - 1) + "}");
          if (wordCount &gt;= maxWords)
          {
              field.value = value.match(re);
          }
          document.getElementById('description_count').innerHTML = maxWords - wordCount;
      }
  &lt;/script&gt;
  </code></pre>