Lefteris Gkinis
Lefteris Gkinis

Reputation: 1259

Function is undefined using javascript

In my ASP.NET page using the following code:

<asp:ScriptManager  ID="ScriptManager1" runat="server"></asp:ScriptManager>
<script type="text/javascript" language="javascript">
        function ValMail() {
        var txt = document.getElementById("<%= Email.ClientID%>");
        var Resp = <%IsValidEmail(Email.Text)%>;
        if (Resp != false)
            txt.nodeValue = "";
            txt.focus();
            };
    </script>
    <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">E-mail:</asp:Label>
    <asp:TextBox ID="Email" runat="server" TabIndex="4" CssClass="textEntry" CausesValidation="True" ></asp:TextBox>
<asp:Button ID="TestButton" runat="server" OnClientClick="ValMail()" />

My problem is that when I click on the button comes to executes the command OnClientClick="ValMail()"
Holds the execution of the program and throw me an error javascript runtime error: ValMail() is undefined
But even sow I'm clicking Ignore and the code goes into the script executes only the line var Resp = <%IsValidEmail(Email.Text)%>; and nothing from the rest of the code in javascript
I’m completely unfamiliar with javascript coding and most with the thrown errors. Is someone to assist me with that?

Upvotes: 0

Views: 244

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

I can't explain the "ValMail() is undefined" error. However, if you use your browser's "View Page Source" option I think you'll find that this line:

var Resp = <%IsValidEmail(Email.Text)%>;

...is sent to the browser as this:

var Resp = True;

or:

var Resp = False;

Either of which is a syntax error in JavaScript because JS is case sensitive and you need a lowercase t or f in the boolean true and false. So either modify that ASP code to put out true or false in all lowercase or add quotes so that JS treats it as a string and then tests as a string with the matching uppercase F:

var Resp = "<%IsValidEmail(Email.Text)%>";
if (Resp != "False")

Which, given that Resp is only used in one place after its declaration, you could shrink down to:

if ("<%IsValidEmail(Email.Text)%>" != "False") {

Also I think you want txt.value, not txt.nodeValue.

Finally, judging by the indenting, I suspect you want both lines under the if to belong to the if, in which case they need to be contained in a block designated by { and } - you currently have no opening { which means only the line immediately after the if belongs to it.

Putting that all together:

function ValMail() {
    var txt = document.getElementById("<%= Email.ClientID%>");
    if ("<%IsValidEmail(Email.Text)%>" != "False") {
        txt.value = "";
        txt.focus();
    }
}

Upvotes: 1

Related Questions