Introduction
When I wrote the article KeyPress Event of TextBox in ASP.NET , someone asked me how to type something into a TextBox in ASP. NET and at the same time, the text appears in a label, so this article helps you to do that.
As I said previously in my article, an ASP.NET text box does not provide a "KeyPress" event, but you can implement it using some simple JavaScript code, and if you want to see that code, then you can go to my previous article, and this article builds upon that. Now let's proceeed with how to implement that functionality.
I am writing a simple code by which you can "type something into an ASP. NET TextBox and at the same time, the text appears in a label".
Example
The following code is the same as that provided previously in the "KeyPress Event of TextBox in ASP.NET" article. In addition, I have implemented some extra functionality to do the "type something into an ASP. NET TextBox and at the same time, the text appears in a label" purpose. The following code in bold shows the core concepts indicating how to do that. In this code I use a var "lbl" variable to access the id of the ASP label using document.getElementByID("write label id here") for assigning the TextBox value and also I do the same with the TextBox to get the TextBox value when the user writes inside the TextBox, in other words when the user presses a key inside the TextBox.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" lang="js">
$(function () {
$("input[type=text]").keypress(function () {
var lbl = document.getElementById("l1");
var TestVar = document.getElementById('<%= t1.ClientID %>').value;
lbl.innerHTML = TestVar;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="t1" runat="server"
style="top: 54px; left: 354px; position: absolute; height: 22px; width: 128px"></asp:TextBox>
<asp:Label ID="l1" runat="server"
style="top: 91px; left: 359px; position: absolute; height: 19px; width: 213px"></asp:Label>
<asp:Label ID="Label1" runat="server" ForeColor="#FF6600"
style="top: 53px; left: 107px; position: absolute; height: 19px; width: 223px"
Text="Write Some thing inside TextaBox"></asp:Label>
<asp:Label ID="Label2" runat="server" ForeColor="#FF6600"
style="top: 90px; left: 130px; position: absolute; height: 19px; width: 166px"
Text="See result in Lebel"></asp:Label>
</form>
</body>
</html>
Output