0

I'm trying to reset my form using javascript on client side. The code looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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 runat="server">
    <title></title>
    <script type="text/javascript" >
        function Reset() {
            TextBox1.text = "";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Reset()" />
    </div>
    </form>
</body>
</html>

This of course isn't working, I get the error that Button1 is undefinded. I tried looking control's name within browser (by viewing page source) and using that instead of its ID but that didn't work either.

atoMerz
  • 7,534
  • 16
  • 61
  • 101

2 Answers2

1

you need to get the value using getElementById

var mybutton= document.getElementById('Button1');
mybutton.value = ""
Richard Forrest
  • 3,567
  • 2
  • 23
  • 32
1

I advise you to use jQuery for your javascript code. It's a standard anyway.

After you reference jQuery, you may rewrite your JavaScript as follows:

<script type="text/javascript" >
    function resetForm() {
        $("#<%=TextBox1.ClientID %>").val("");
    }
</script>    

If you still do not want to use jQuery, then you need to access your element using its client ID like following:

<script type="text/javascript" >
    function resetForm() {
        document.getElemenyById("<%=TextBox1.ClientID %>").value = "";
    }
</script>    

Also, as @Jon pointed out, you need to either rename your OnClientClick value to resetForm() or rename your JavaScript function.

Zruty
  • 8,377
  • 1
  • 25
  • 31
  • One Question, what are those odd characters and why won't it work when I remove 'em? – atoMerz Aug 12 '11 at 11:07
  • What odd characters? You mean <% %> these ones? This is a placeholder: the server will insert the value (`TextBox1.ClientID`) there in the response – Zruty Aug 12 '11 at 12:45
  • Thanks, Is there any place I can read more on this? I mean placeholder and stuff (not jQuery) or is it jQuery? – atoMerz Aug 16 '11 at 14:06
  • That's a tough question for me. It appears that these characters are ASP tags, and their history starts in 1998. You can read about them here: http://www.georgehernandez.com/h/xComputers/ASP/ASPTags.asp – Zruty Aug 16 '11 at 14:58
  • Basically, these tags enclose the 'server-run' area on your ASPX page. Everything inside <% %> is run on the server, and everything else is transmitted to the client's browser – Zruty Aug 16 '11 at 14:59
  • 1
    Also, see this link: http://naspinski.net/post/inline-aspnet-tags-sorting-them-all-out-(3c25242c-3c253d2c-3c252c-3c252c-etc).aspx – Zruty Aug 16 '11 at 15:01