calling JavaScript function from VB

maqskywalker
maqskywalker used Ask the Experts™
on
I'm trying to call a JavaScript function from VB on button click.

Below is my code.
Why is the alert message not coming up when I click the button?

Call_JSFunctionFromVB1.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Call_JSFunctionFromVB1.aspx.vb" Inherits="TelerikWindow3Level.Call_JSFunctionFromVB1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function HelloFunctionVB1() {
            alert('Hello you called a JS function from VB')
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Button" />
    </div>        
    </form>
</body>
</html>

Open in new window


Call_JSFunctionFromVB1.aspx.vb


Public Class Call_JSFunctionFromVB1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' ----- call JavaScript function -----
        Dim script As String = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(HelloFunctionVB1);</script>"
        ClientScript.RegisterStartupScript(Me.[GetType](), "showWindow", script)
        ' ----- call JavaScript function -----

    End Sub


End Class

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer
Top Expert 2011
Commented:
Why not just use the OnClientClick attribute of the Button control :

<asp:Button ID="Button1" OnClick="Button1_Click" OnClientClick="return HelloFunctionVB1()" runat="server" Text="Button" />

Open in new window


also need to add a return in javascript function as below, this just stops the form doing a server side submit. If you wanted it to execute the Server Side event Button1_Click then either take out the return false; or set it to return true; depending on your requirements.

<script type="text/javascript">
        function HelloFunctionVB1() {
            alert('Hello you called a JS function from VB');
            return false;
        }
</script>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial