Validating textbox using javascript in MasterPage
I am using javascript for customValidator to validate textboxes in ASP.Net. The code works perfectly when I am using a normal page, but as soon as I put that inside a MasterPage, the code doesn't work.
Below is the code for my aspx page. If I put this code inside a MasterPage it doesn't work. Could you guys advise me how to make this work inside a MasterPage
Thanks, Abhi.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server开发者_Python百科">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function validateOrFields(source, args){
var sUser = document.getElementById('TextBox1');
if (sUser.value == "")
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
return;
}
<div>
<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
<asp:CustomValidator ID="FieldValidator"
runat="server"
Text="Enter either a user name"
ClientValidationFunction="validateOrFields" onservervalidate="FieldValidator_ServerValidate"/>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
The problem is the ID of the TextBox. When placed in the Master Page, it gets a different ClientID.
var sUser = document.getElementById('<%= TextBox1.ClientID %>');
you need to get the id by using ClientID
Replace your code by
var sUser = document.getElementById('<%= TextBox1.ClientID %>');
Try document.getElementById('ct100_TextBox1').value. It is just a temporary fix!! But anyone please suggest how to get this ID dynamically using code. I got this by viewing source of the page generated. I have also posted the same question here link text
精彩评论