简体   繁体   中英

How to count no. of characters entered in multiline textbox till 140 characters

How to count no. of characters entered in multiline textbox, i wanna enter maximum 140 characters in my multiline textbox using vb.net ...

In short i want textbox to enter limit is only 140 characters ....

i have te following code to do that .... but i wanna implement 140 characters limit in multiline textbox :

<script type="text/javascript">
        function Count(x) {

           document.getElementById("Label1").innerHTML = document.getElementById("TextBox2").value.length;
        }
</script>


<asp:TextBox ID="TextBox2" runat="server" Height="78px" 
            TextMode="MultiLine" Width="224px" onkeyup="Count(this.id)" 
            MaxLength="140"></asp:TextBox>

Since you tagged your question with asp.net I'm assuming you're talking about a web application.

If it is so, this job is best done by a client side script like JavaScript, and not VB.NET, you should use the latter to do a server side check only after the user has submitted the form, and use the former while he is still entering the data.

On the internet there are many examples on how to do this, just look for something like " javascript count characters ".

Here's an example of how to do this. The function takes the number of characters you're limiting to, the (client, HTML) id of the control to count, and the id of the element to output the count into

<script type="text/javascript">
    function CountChars(charLimit, inputId, outputId) {
        var remainingChars = charLimit - document.getElementById(inputId).value.length;
        document.getElementById(outputId).innerHTML = remainingChars;
    }   
</script>

And here's a usage example

    <asp:TextBox ID="TextBox2" Width="100%" TextMode="MultiLine" Rows="10" MaxLength="140"
        runat="server"></asp:TextBox>
</p>
<p>
    Characters remaining: <span id="characterCount">140</span></p>

Hook up the event handler in code behind, in the page load event:

Protected Sub AddCharCountHandler()
    TextBox2.Attributes.Add("onkeyup", "CountChars(" & 140 & ", '" & TextBox2.ClientID & "'," & "'characterCount');")
End Sub

Note that I'm calling the function using txtDescription.ClientId, although my output span has a fixed id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM