Problem when I place javascript in $(document).ready
Hi I am having following code working fine when placed without $(document).ready
<asp:TextBox ID="TextBox_FirstName" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox_LastName" runat="server"></asp:TextBox>
<asp:Button ID="txtSubmit" Text="Validate" runat="server" />
<asp:CustomValidator ID="AtLeastOneTextBoxValidator" runat="server"
ClientValidationFunction="Validate_Textbox" ValidateEmptyText="true">
</asp:CustomValidator>
function Validate_Textbox(sender, args) {
var firstName = document.g开发者_运维知识库etElementById("<%= TextBox_FirstName.ClientID %>");
var lastName= document.getElementById("<%= TextBox_LastName.ClientID%>");
if ((firstName == "") && (lastName == "")){
window.alert("Error");
}
}
When I placed this code inside $(document).ready it is giving 'Microsoft JScript runtime error: Object expected' error.
$(document).ready( function(){
function Validate_Textbox(sender, args) {
var firstName = document.getElementById("<%= TextBox_FirstName.ClientID %>");
var lastName = document.getElementById("<%= TextBox_LastName.ClientID%>");
if ((firstName == "") && (lastName == "")){
window.alert("Error");
}
}
});
You're now declaring the Validate_Textbox
function inside another (anonymous) function. Like all variables, it is now usable only inside that function. You won't be able to use it anywhere else in your application.
There's no functional advantage to declaring functions inside a $(document).ready()
callback. The better question is: where is Validate_Textbox
called?
That's happening because something's looking for your Validate_Textbox
function which is not defined only in that document.ready
handler's scope, not globally...so outside that document.ready
handler, Validate_Textbox
doesn't exist...when you call it, you get your error.
You should have this outside of the $(document).ready block as it is a self contained function and will be called from code within the $(document).ready block.
精彩评论