views:

2417

answers:

8

I have an asp button. It's server-side so I can only show it for logged in users, but i want it to run a javascript function and it seems when it's runat="server" it always calls the postback event.

I also have a regular button (<input...>) not running at server and it works fine...

How can I make this button only run the javascript and not postback?

A: 

You need to return false from your function.

Andrew Robinson
A: 

Set the OnClientClick property to return false or have your javascript function do it.

Brandon
+10  A: 

Have your javascript return false when it's done.

<asp:button runat="server".... OnClientClick="myfunction(); return false;" />
womp
I think you mean `OnClientClick="myfunction(); return false;"` for the JavaScript
Adam Pope
Thanks for the edits ;)
womp
A: 
YourButton.Attributes.Add("onclick", return false");

or

<asp:button runat="server" ... OnClientClick="return false" />
Koistya Navin
A: 

You don't say which version of the .NET framework you are using.

If you are using v2.0 or greater you could use the OnClientClick property to execute a Javascript function when the button's onclick event is raised.

All you have to do to prevent a server postback occuring is return false from the called JavaScript function.

OtisAardvark
A: 

The others are right that you need your callback to return false; however I'd like to add that doing it by setting the onclick is an ugly old way of doing things. I'd recommend reading about unobtrusive javascript. Using a framework like jQuery could make your life easier, and the HTML less coupled to your javascript (and jQuery's supported by Microsoft now!)

Neil Williams
A: 

Either use the "return false" approach mentioned by others, or add the runat="server" attribute to your normal button:

<input type="button" runat="server" id="htmlButton" ...>

Then you can set the HTML button's visibility property in the codebehind, e.g:

htmlButton.Visible = isLoggedIn;
M4N
A: 

This works fine:

<asp:Button CssClass="button" runat="server" ID="btnClear" OnClientClick="clearinputs();return false;"/>
Gert