How to clear all text fields in an ASP.NET page using JavaScript

Let’s say you have 3 textboxes in your page. You want to remove their contents by clicking a button. Here is your front-end code:

<asp:TextBox ID="txtOldPassword" MaxLength="30" runat="server" TextMode="Password" Width="150px" TabIndex="1"></asp:TextBox>
<asp:TextBox ID="txtNewPassword" MaxLength="50" runat="server" TextMode="Password" Width="150px" TabIndex="2"></asp:TextBox>
<asp:TextBox ID="txtConfirmPassword" MaxLength="50" runat="server" TextMode="Password" Width="150px" TabIndex="3"></asp:TextBox>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" OnClientClick="clearTextFields();" TabIndex="4" />

You can remove their contents by using the simple script below.

var elements = document.getElementsByTagName("input");
for (var i=0; i < elements.length; i++) {
     if (elements[i].type == "password") {
          elements[i].value = "";

Note: In my example, all textboxes are “password” fields. You can easily adjust this script to “text” fields. You just need to change elements[i].type == "password" to elements[i].type == "text"

Leave a Reply