简体   繁体   中英

Cannot get a form in javascript from a .NET page?

I have a typical .NET page with a master page. The web page has an asp:Button that calls a javascript function Form_Validator() . I cannot get the Form inside the Form_Validator() function no matter what I try. It is always null.

I've tried the traditional method of passing the Form like this too: OnClientClick="Form_Validator(this.form); , but nothing is working. I just feel it has something to do with the masterpage?

<asp:Button ID="cmdSubmit" runat="server" Text="Submit" OnClientClick="Form_Validator();" OnClick="cmdSubmit_Click" />

<script type="text/javascript">
function Form_Validator() {
var theForm = document.getElementById(this.Form1);
alert(theForm);
</script>

It probably does have to do with the Master Page, as ASP.NET will use a naming convention like "[Content Placeholder ID]_[Control]". This should work though:

var theForm = document.forms[0];

Alternatively, you can try setting "ClientIDMode" (in the page directive) to "static", which will tell ASP.NET to assign IDs the way you tell it to, and not use all the crazy nested naming conventions.

ASP.net features ClientID which is the ID as rendered to the page. You could use

<script type="text/javascript">
   function Form_Validator() {
   var theForm = document.getElementById("<%=this.Form1.ClientID%>");
   alert(theForm);
</script>

which will insert the FormID as rendered to the page into your javascript. If you are not using "Static" client id mode this will be the way you access other form elements too.

Eg:

<form id="Form1" runat="server">
     <asp:TextBox ID="txtABox" runat="server" />
</form>
<script type="text/javascript">
   function Form_Validator() {
   var theForm = document.getElementById("<%=this.Form1.ClientID%>");
   alert(theForm);
   var aBox = document.getElementByID("<%=txtABox.CLientID%>")
</script>

On a side note I would look at the inbuilt asp.net form validators . There is also a good indepth look at asp.net validators .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM