Max number of words in textarea using jQuery

Here is a little code snippet to set a maximum of words in a text area element.

This could be turned into a jQuery function or refactored to be better reused, but there is a sample just to get you going.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$('textarea').keyup(function () {
            var wordArray = this.value.split(/[\s\.\?]+/); //Split based on regular expression for spaces
            var maxWords = 5; //max number of words
            var total_words = wordArray.length; //current total of words
            var newString = "";
            //Roll back the textarea value with the words that it had previously before the maximum was reached
            if (total_words > maxWords+1) {
                 for (var i = 0; i < maxWords; i++) {
                    newString += wordArray[i] + " ";
                }
                this.value = newString;
            }

        });

Using UserControl.RenderControl()

Perhaps you want to reuse a usercontrol in a email? or you need to generate the html from a usercontrol for a specific purpose?

Firstly, here is the code to render the html from a user control to a string builder object:

1
2
3
4
5
6
7
8
9
   Dim sb As New StringBuilder()
   Using sw As New StringWriter(sb)
      Using htmlTw As New HtmlTextWriter(sw)
          Dim ucUserControl As UCUserControl = LoadControl("myUserControl.ascx")
          ucUserControl .Visible = True
          ucUserControl .Display() 'This is a custom method to do some processing
          ucUserControl .RenderControl(htmlTw)
      End Using
   End Using

Secondly, make sure that you set enableEventValidation=”false” on the page you are generating the html from. You will get an error if this is enabled. You could extend this futher by adding a boolean variable to the page and only disabling Event Validation while rending the control.

Thirdly, override the VerifyRenderingInServerForm method and make it doing “nothing”. If you do not do this, you will get an error saying that you have no form sever tag in your user control.

1
2
3
Public Overrides Sub VerifyRenderingInServerForm(control As System.Web.UI.Control)
'Do nothing
End Sub