How to clear textbox in asp.net using JavaScript

{0 Comments}

While I was working on a project I have to clear a text box in asp.net by using a JavaScript function. Then after I developed the following function which helps you to understand how to clear a text box in asp.net by using JavaScript function.

For this take a web form then, add a text box here its id is txt_clear, and two button one will apply a value to textbox using javascript and other in same manner clear it. Following is my javascript functions:

 Javascript |  copy code |? 
01
function val_check()
02
      {
03
        document.getElementById('txt_clear').value = "1234";
04
      }
05
      function clr()
06
      {
07
        document.getElementById('txt_clear').value = "";
08
      }
09
 
10

Here val_check() function will add 1234 to txt_clear textbox. And clr() function will clear the value form the textbox.  So the final source code will look like this:

 HTML |  copy code |? 
01
<head runat="server">
02
    <title>Untitled Page</title>
03
    <script type="text/javascript">
04
        function val_check()
05
      {
06
        document.getElementById('txt_clear').value = "1234";
07
      }
08
      function clr()
09
      {
10
        document.getElementById('txt_clear').value = "";
11
      }
12
 
13
    </script>
14
 
15
</head>
16
<body>
17
    <form id="form1" runat="server">
18
    <div>
19
        <asp:TextBox ID="txt_clear" runat="server"></asp:TextBox>
20
        <asp:Button ID="btn_add" runat="server" Text="ADD" OnClientClick="val_check()" />
21
        <asp:Button ID="btn_clr" runat="server" Text="Clear" OnClientClick="clr()" />
22
    </div>
23
    </form>
24
</body>
25
 
26

In above code when you click the add button it will call val_cheack function and clear button will call clr function would clear the value form the text box. you can download sample file by cleattxtbox

Leave a Comment

Your email address will not be published.