Problem reseting a form on client side with ASP.NET
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></tit开发者_如何学运维le>
<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.
you need to get the value using getElementById
var mybutton= document.getElementById('Button1');
mybutton.value = ""
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.
精彩评论