7

I have a textarea in C#, please see below code:

<asp:Label ID="lblQuestions" runat="server" CssClass="addinfo">
                    Question & Comments</asp:Label>
<asp:TextBox ID="txtQuestions" Rows="5" Columns="5" TextMode="MultiLine" runat="server" MaxLength="250"></asp:TextBox>

Now I want that textarea should not accept more than 250 characters, whatever user do COPY & PASTE, by WRITING and DRAG & DROP etc, if user try to copy or drag & drop more than 250 character the first 250 characters should be copied in textarea. I know that there no MAXLENGTH attribute in TEXTAREA. If it is not possible with .NET the solution with javascript or Jquery will work.

Please help

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Manoj Singh
  • 7,569
  • 34
  • 119
  • 198
  • This seems to be a duplicate of this question http://stackoverflow.com/questions/1334286/specifying-maxlength-for-multiline-textbox/1334343#1334343 – Raúl Roa Sep 08 '09 at 19:43
  • Except that question's answer only works in IE - and is kinda ugly - and doesn't work with right click copy/paste or drag/drop. – gnarf Sep 08 '09 at 21:21

7 Answers7

3

You have to wire functions for the events

onpaste, onkeyup and onfocus of the area for which you want to do this action.

For an asp textbox I think you have to consider only OnTextChanged event.

For textarea

<INPUT id="counterMessage" readOnly size="3" value="250" name="counterMessage">                                                                                                     
<TEXTAREA onpaste="PasteCounter(this.form.txtAreaMessage,this.form.counterMessage,250);"
                                                                                                                            id="txtAreaMessage" onkeyup="textCounter(this.form.txtAreaMessage,this.form.counterMessage,250);"
                                                                                                                            style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; OVERFLOW: hidden; BORDER-LEFT: 0px; WIDTH: 99%; BORDER-BOTTOM: 0px; HEIGHT: 95px; TEXT-ALIGN: justify"
                                                                                                                            onfocus="textCounter(this.form.txtAreaMessage,this.form.counterMessage,250);" name="txtAreaMessage"
                                                                                                                            rows="3" runat="server"></TEXTAREA>


function PasteCounter(field, countfield, maxlimit)
        {
            var len;
            var txt = clipboardData.getData("Text");
            txt = field.value + txt
            len = parseInt(txt.length);
            if ( len >  maxlimit )
            {
                event.returnValue=false;
                txt = txt.substring(0, maxlimit);       
                field.value = txt;                  
                alert("Only " + maxlimit + " characters are allowed");
            }
            countfield.value = maxlimit - txt.length;
        }    
        function textCounter(field, countfield, maxlimit)
        {
            if (field.value.length > maxlimit )
            {      
                field.value = field.value.substring(0, maxlimit );
                alert("Only " + maxlimit + " characters are allowed");
            }
            countfield.value = maxlimit - field.value.length;
        }

The countfield textbox is for showing remaining characters.

rahul
  • 184,426
  • 49
  • 232
  • 263
3

You can use jQuery to bind to multiple events at once

$("#txtQuestions").bind("keyup change blur input paste", function() {
  // fire this off a few ms after the event happens
  setTimeout(
   (function(el){ // closure to store "this" as "el"
     return function() { if (el.value.length>250) el.value.length = 250; }
   })(this), 10);
});

There is a library (jQuery.charcounter) out there that will automatically add the characters remaining and what not to the DOM as well.

gnarf
  • 105,192
  • 25
  • 127
  • 161
2

You can do this with an ASP.NET validator as well:

<asp:TextBox ID="MyTextBox" runat="server" TextMode="MultiLine" Rows="4" />
<asp:RegularExpressionValidator Display="Dynamic" ID="RegularExpressionValidator1" ControlToValidate="MyTextBox" Text="<p>A maxiumum of 250 characters is allowed.</p>"  runat="server" ValidationExpression="^(.|\s){0,250}$" />
Andrew Barrett
  • 19,721
  • 4
  • 47
  • 52
1

1) A very simple way to handle this is to start with the onChange event:

<textarea id="yourTextArea" onchange="this.value.length = Math.min(this.value.length, 250)"></textarea>

The major drawback here is that the textarea will not update until the focus has left the textarea.

2) You should be able to adapt the above example to a form validation function that fires on the form's onSubmit event.

<script type="text/javascript">
    document.forms[0].onsubmit = function() { document.getElementById("yourTextArea").value.length = Math.min(this.value.length, 250); }
</script>

3) If you want to do this validation on the server side, you really just need to get the textarea's value and truncate it.

string validText = yourTextArea.Value.Substring(0, 250);
Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125
1

Expanding on @gnarf's answer:

<textarea class="max-length" cols="30" id="comment-box" maxlength="250" rows="10"></textarea></span>
<span id="comment-box-chars-left">250</span> characters left
<script type="text/javascript>
    function updateCharsLeft(id, maxChars, length) {
        $('#' + id + '-chars-left').html(maxChars - length);
    }

    $(document).ready(function() {
        $('.max-length').each(function() {
            updateCharsLeft($(this).attr('id'), $(this).attr('maxLength'), $(this).val().length);
        });

        $('.max-length').bind('keyup change blur input paste', function() {
            var maxChars = $(this).attr('maxLength');

            // fire this off a few ms after the event happens
            setTimeout((function(el) { // closure to store "this" as "el"
                return function() {
                    if (el.value.length > maxChars) {
                        el.value = el.value.substring(0, maxChars);
                    }
                    updateCharsLeft(el.id, maxChars, el.value.length);
                }
            })(this), 10);
        });
    });
</script>

This uses an attribute, to specify the maximum number of characters and updates a label displaying the number of characters left as well. The text area must be given the class max-length and the element that will display the number of characters left, must have the same id as the corresponding text area with -chars-left appended to it.

s1mm0t
  • 6,035
  • 4
  • 38
  • 45
0

For interactive feedback, you should do the above in javascript, as wired controls will not react until it is posted back to the server (requiring a page reload). This can cause quite a bit of server load if you update character counts on every keystroke.

Below is a rough js implementation that will simply count the number of ASCII characters on every change. This will also work if the textarea is modified due to cut and pasting:

<script type="text/javascript">
function countWords() {
var text = document.getElementById("txtBox1").value;
if (text.length > 250) text = text.substr(0,250);
document.getElementById("txtBox1").value = text;
}
</script>

<textarea id="txtBox1" onkeyup="countWords();" >text here</textarea>
futureelite7
  • 11,462
  • 10
  • 53
  • 87
0
<asp:TextBox
    onkeypress="return value.length<=10;"
    onpaste="return (value.length+clipboardData.getData('Text').length)<=10"
    TextMode="MultiLine"
    runat="server"  
/>
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632