How to access ASP.Net TextBox control in JavaScript

Introduction

In the following code snippet, we will see that how we can get the value of the ASP.Net TextBox in JavaScript.

Get the value of the ASP.Net Textbox in javascript

To get the value of the ASP.net textbox control, use the javascript code like as:

var name = document.getElementById("<%=txtname.ClientID %>").value;

To set the innerHTML of the ASP.Net labal control, use the code like as:

document.getElementById("<%=lblAmount.ClientID %>").innerHTML = "Welcome " + name

Full source of .aspx page

The complete example to get the value of the ASP.Net Textbox is shown below:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function getvalues() {
            var name = document.getElementById("<%=txtname.ClientID %>").value;
    document.getElementById("<%=lblAmount.ClientID %>").innerHTML = "Welcome " + name
            return false;
        }
    </script>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter your name:<asp:TextBox ID="txtname" runat="server" /><br />
        <asp:Button ID="btnValidate" runat="server" Text="Submit" 
                  OnClientClick="return getvalues();" /><br />
 
       <asp:Label ID="lblAmount" runat="server" />
    </div>
    </form>
</body>
</html>