Blerta
Blerta

Reputation: 2190

Asp.net Counting Number of Characters being written in a textbox

I want to be able to display current number of characters, in a asp label, written in a textbox while the user is currently writting in it. I've read partial articles on the web but none of them works.

I've tried using

<asp:TextBox ID="txtInput" runat="server" TextMode="MultiLine" onkeyup="Count(this.id)"></asp:TextBox>

and

<script type="text/javascript">
        function Count(x) {
           document.getElementById(lbNrChar).value = document.getElementById(x).value.length;
        }
</script>

but without any success..

Upvotes: 0

Views: 15224

Answers (3)

Ben Lesh
Ben Lesh

Reputation: 108471

I haven't tested this but hopefully it helps. If you're doing this in a UserControl, you'll have to alter it a bit if you're putting the same user control on the page more than once. (Basically you'd have to register the javascript from the codebehind).

In your code behind (Init or Load or somewhere like that):

txtInput.Attributes["onkeydown"] = String.Format("count('{0}')", txtInput.ClientID);

ASPX

<asp:TextBox id="txtInput" runat="server" TextMode="MultiLine"/>
Count: <span id="spanDisplay"></span>

<script type="text/javascript">
  function count(clientId) {
    var txtInput = document.getElementById(clientId);
    var spanDisplay = document.getElementById('spanDisplay');
    spanDisplay.innerHTML = txtInput.value.length;
  }
</script>

Upvotes: 0

Kevin LaBranche
Kevin LaBranche

Reputation: 21078

we used Javascript to solve this:

document.getElementById(value).value.length...

Note that if the control is a label then you have to use the .innerHTML not .value property for it to take the length.

    document.getElementById("Label1").innerHTML = 
document.getElementById("TextBox1").value.length; 

vs. if it's another text box you would use .value.

on the server side you can get it by textbox.text.length

Upvotes: 3

cfeduke
cfeduke

Reputation: 23226

You will need to use a client-side scripting language hosted in the browser - basically you will have to use JavaScript.

This question answers fairly well the behind the scenes of what you want to do. You'll need to handle the onKeyPress client-side event of the text boxes and text areas you want to track, and placing the label, script, and text controls in a ASP.NET UserControl wouldn't be a bad approach.

Edit: since the linked question doesn't go indepth any further, you'll need jQuery (and you'll realize how much fun web UI programming can be again when you start using it) and I suspect this article will help you understand how to get the ball rolling.

Upvotes: 2

Related Questions