143

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?

13 Answers 13

281

Have your javascript return false when it's done.

<asp:button runat="server".... OnClientClick="myfunction(); return false;" />
Sign up to request clarification or add additional context in comments.

4 Comments

In many cases people use an onclick or OnClientClick with this syntax <asp:Button OnClientClick="myFunction()" /> where myFunction() returns false and this isn't enough - you have to use OnClientClick="return myFunction()"
I had to add UseSubmitBehavior="False" as well as ;return false
Make sure to add 'CausesValidation="false"', otherwise it will add 'WebForm_DoPostBackWithOptions' and a bunch of extra markup.
This didn't work for me in ASP.NET 4+, however Konstantin's answer of simply OnClientClick="return false" did work.
41
YourButton.Attributes.Add("onclick", "return false");

or

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

Comments

16

You can use jquery click action and use the preventDefault() function to avoid postback

<asp:button ID="btnMyButton" runat="server" Text="MyButton" />


$("#btnMyButton").click(function (e) {
// some actions here
 e.preventDefault();
}

6 Comments

This is an elegant answer because it allows you to test for conditions to disable.
Never use preventDefault as it will stop other events that rely on this event -1
@ppumkin: preventDefault is a great way to tell other event listeners that you handled this event so they don't have to do so. I think what you meant was stopPropagation, which indeed stops the event from even being heard by other event listeners.
Yeaaaaaaaaaa. no. 4 Years later and I stand behind this even more now. Just don't do any of that.
@PiotrKula How about another 4 years later? You can't just say dont do that. Obviously it's fine for the vast majority of cases. And convenience is worth a lot.
|
8

Consider this.

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequest);
function BeginRequest(sender, e) {
    e.get_postBackElement().disabled = true;

}
     </script>

1 Comment

A bit more context to your answer would be nice
6

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 library like jQuery could make your life easier, and the HTML less coupled to your javascript (and jQuery's supported by Microsoft now!)

Comments

5

ASP.NET always generate asp:Button as an input type=submit.
If you want a button which doesn't do a post, but need some control for the element on the server side, create a simple HTML input with attributes type=button and runat=server.

If you disable click actions doing OnClientClick=return false, it won't do anything on click, unless you create a function like:

function btnClick() {
    // do stuff
    return false;
}

Comments

3

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.

Comments

3

additionally for accepted answer you can use UseSubmitBehavior="false" MSDN

1 Comment

ASP.NET adds ;__doPostBack( to the end of client click script.
3

In my case, I solved adding return in the onClientClick:

Code Behind

function verifyField(){
  if (document.getElementById("inputId").checked == "") {
    alert("Fill the field");
    return false;
  }
}

Design Surface

<asp:Button runat="server" ID="send" Text="Send" onClientClick="return verifyField()" />

1 Comment

How to run OnClick method after this.
2

you can use the code:

<asp:Button ID="Button2" runat="server"
     Text="Pulsa"
     OnClientClick="this.disabled=true"
     UseSubmitBehavior="False"/>

if nee submit

...
<form id="form1" runat="server" onsubmit="deshabilita()">
...
<script type="text/javascript">
    function deshabilita()
    {
        var btn = "<%= Button1.ClientID %>";
        if (confirm("Confirme postback"))
        {
            document.getElementById(btn).disabled = true;
            return true;
        }
        return false;
    }
</script>

Comments

2

With Validation

In this example I used two controls,ddl and txtbox, have a happy coding

 asp:ScriptManager ID="script1" runat="server" /asp:ScriptManager

    asp:UpdatePanel ID="Panel1" runat="server"
       ContentTemplate

// ASP BUTTON
asp:Button ID="btnSave" runat="server" Text="Save" class="btn btn-success" OnClientClick="return Valid()" OnClick="btnSave_Click"


   /ContentTemplate    
    /asp:UpdatePanel    

  <script type="text/javascript">
        function Valid() {

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val() == 0) {
                alert("Please select YOUR TEXT");
                $("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }

            if ($("#ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").val().length == 0) {
                alert("Please Type YOUR TEXT");
                $("ctl00_ContentPlaceHolder1_YOUR CONTROL NAME").focus();
                return false;
            }
            return true;
        }
</script>

Comments

2

You can use JQuery for this

<asp:Button runat="server" ID="btnID" />

than in JQuery

$("#btnID").click(function(e){e.preventDefault();})

Comments

1

You just need to return false from the

function jsFunction() {
  try {
    // Logic goes here
    return false; // true for postback and false for not postback
  } catch (e) {
    alert(e.message);
    return false;
  }
}
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />

JavaScript function like below.

Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.