Abhishek gupta
Abhishek gupta

Reputation: 463

Script doesn't call

I have a simple asp page with a script including a function myFunction which performs an addition of two numbers.

<head runat="server">
    <title></title>

     <script type="text/javascript">
         function myFunction() {
             var x = 10;
             var y = 5;
             x += y;
             var demoP = document.getElementById("demo")
             demoP.innerHTML = "x=" + x;
         }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        
    <div>
               
    </div>
    <p>
        &nbsp;</p>
    <p id="demo">
        <asp:Button ID="Button1" runat="server"
            
            style="z-index: 1; left: 573px; top: 43px; position: absolute; height: 33px; width: 223px;" Text="Button" OnClick="myFunction()" />
    </p>
   
    </form>
</body> 

When I run this page it shows an error that myFunction is not found.

Upvotes: 0

Views: 248

Answers (4)

Prince Antony G
Prince Antony G

Reputation: 932

 protected void Page_Load(object sender, EventArgs e)
 {
     Button1.Attributes["onclick"] = "javascript:myFunction();";
 }

You want to call a javascript function in code behind page, use this.

Upvotes: 2

Charlie
Charlie

Reputation: 1332

When you want to call a javascript function use this

<input type="button" id="Button1" value="Button" onclick="myFunction()" />

Controls with <asp: is server side control and the OnClick event will call a server side method. There is no "myFunction" method defined in your code behind file, so you will get a server side error.

Upvotes: 0

Sanjeev Rai
Sanjeev Rai

Reputation: 6982

To call a javascript function from aspbutton you have to use 'onclientclick' event insteed of 'onclick' event of button.

try using this

OnClientClick="myFunction()"

Otherwise you can also use 'OnClick' event of any html control like, 'anchor tag', 'div', 'input' etc. For example:

<a href= "#" OnClick="myFunction()" > Click to call function</a>

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

OnClick is for server side callback. You want to invoke a client side function. So you should use OnClientClick instead:

OnClientClick="myFunction()"

Upvotes: 5

Related Questions