How do I show a countdown on character length in a TextBox?

  • Thread starter Richard Gadsden
  • Start date
R

Richard Gadsden

I've got a text box called txtMessage and a label called lblSize.

I've set txtMessage.MaxLength to 160 (yes, this is an SMS application) and
I want lblSize to show a countdown as the user types so they know how much
space they have left.

I've put a TextChanged event on txtMessage with:

lblSize.Text = 160 - txtMessage.Text.Length

and when you tab out of the txtMessage box, it counts down. But I want it
to count continuously as the user types.

What am I doing wrong, or is the whole approach wrong - would I need a
CustomValidator, or perhaps a completely client-side solution?
 
K

Ken Cox [Microsoft MVP]

Hi Richard,

You going to have to use client-side script here to get the events and
immediacy that you want. Server-side is going to be very messy.

Here's a Javascript example of what I suspect you're trying to accomplish.
This will only work in Internet Explorer, but it will give you the idea of
what can be done.

Let us know if it helps?

Ken
Microsoft MVP [ASP.NET]


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>keycount</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
<SCRIPT event="onkeypress" for="txtMessage">
document.all.Label1.innerText=document.all.txtMessage.value.length;
</SCRIPT>
</HEAD>
<body MS_POSITIONING="FlowLayout">
<form id="Form1" method="post" runat="server">
<P>
<asp:TextBox id="txtMessage" runat="server"></asp:TextBox></P>
<P>
<asp:Label id="Label1" runat="server">Label</asp:Label></P>
</form>
</body>
</HTML>
 
R

Richard Gadsden

Hi Richard,

You going to have to use client-side script here to get the events and
immediacy that you want. Server-side is going to be very messy.

Here's a Javascript example of what I suspect you're trying to
accomplish. This will only work in Internet Explorer, but it will give
you the idea of what can be done.

Let us know if it helps?

Brilliant - exactly what I wanted.

All I had to change was document.all.lblSize.innerText = 160 -
document.all.txtMessage.value.length; and then a bit of fenceposting ended
up with a -2 on the end.

Thanks again, especially as I have next to no knowledge of the DHTML
object model that JavaScript is presumably using here; this would have
taken me ages.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,818
Members
47,362
Latest member
eitamoro

Latest Threads

Top