user1448393
user1448393

Reputation: 127

Calling a Javascript function from ASP.NET

My code is:

<body>
<script type="text/javascript">
    function change() {
        alert("Hello");
    }
</script>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="change"/>
</div>
</form>
</body>

The error I get is: CS1061: 'ASP.webform1_aspx' does not contain a definition for 'change' and no extension method 'change' accepting a first argument of type 'ASP.webform1_aspx' could be found.

What is the problem?

Upvotes: 0

Views: 78

Answers (3)

शेखर
शेखर

Reputation: 17614

It should be OnClientClick:-

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return change();"/>

OnClick event is used to bind server side method on button click.

<script type="text/javascript">
    function change() {
        alert("Hello");
        return false;
    }
</script>

Not that the return false will stop the postback cause by the button.
And for this you should also mention return before your function call on button like OnClientClick="return change();"

Upvotes: 1

Dgan
Dgan

Reputation: 10295

OnClick="change" it means that you should Create Method name as change on server Side

Some thing like this

protected void change(object sender,EventArgs e)
{

}

On Server Side

if(!Page.IsPostBack)
{
Button1.Attributes.Add("onclick","change();")
}

on .aspx

<asp:Button ID="Button1" runat="server" Text="Button" />

Upvotes: 1

Rahul Singh
Rahul Singh

Reputation: 21825

It should be OnClientClick:-

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="change"/>

OnClick event is used to bind server side method on button click.

Upvotes: 3

Related Questions