30

Is it possible to use the onclientclick property of a button to do a clientside check. If the check returns true, then fire the onclick event. If the clientside check returns false, don't fire the onclick event.

Is that possible?

UPDATE:

These 2 work:

Stops the form from submitting:
OnClientClick="return false;"

Allows the form to submit:
OnClientClick="return true;"

The next 2 do not work:

// in js script tag
function mycheck() {
    return false;
}

// in asp:button tag
OnClientClick="return mycheck();"

// in js script tag
function mycheck() {
    return true;
}

// in asp:button tag
OnClientClick="return mycheck();"

It submits the form both times.

Why is that?

oshirowanen
  • 15,297
  • 82
  • 198
  • 350

5 Answers5

47

You want to add return inside OnClientClick after a function is called. Otherwise, the button will post back even if function returns false.

<asp:button ID="Button1" runat="server" OnClick="Button1_Click" 
    OnClientClick="return checkValidation()" Text="Submit" />

<script type="text/javascript">
    function checkValidation() {
        return confirm('Everything ok?');
    }
</script>
Sixty4Bit
  • 12,852
  • 13
  • 48
  • 62
Win
  • 61,100
  • 13
  • 102
  • 181
  • Your updated code work. You can test it by creating a new aspx (without master page). It might be something to do with your existing javascript code interfere with the mycheck function. – Win Oct 02 '13 at 15:59
  • Haha! Yes, I was missing the `return` portion of my `OnClientClick`. Thank ya, thank ya! – NocFenix Oct 28 '16 at 14:32
  • This is not entirely accurate. Returning false simply prevents a postback. The the onclick method is still fired on the server side, however its effects are not updated to the screen. If you are using this to prevent say a database update, beware as the event would still fire. – JSON Dec 07 '16 at 20:29
  • 1
    @JSON ***If client doesn't communicate back with server, how does server trigger click event by itself.*** Please note that ***Http is Stateless***. What you mention is not possible unless you use Signal-R which is totally out of the question. *If you have a question, please create one; I'll happy to help you.* – Win Dec 07 '16 at 20:58
  • @Win Perhaps it depends on the type of server you are using. I know for a facts that IIS is like this. I am using it right now and would prove it to you if I could. – JSON Dec 07 '16 at 21:05
  • @JSON As I said if you have question or doubt on how ASP.Net works, please create a new question. Please do not confuse the others with ***incorrect comments***; the answer has been tested by multiple developers, and upvoted 26 times as of today. Otherwise, please kindly delete your comments. – Win Dec 07 '16 at 21:15
  • I'm using ASP .NET WebForms and I got burned by the UseSubmitBehavior="false" in the asp:button tag. If this is false (default is true so not having it is true) then even if the OnClientClick event returns true such as OnClientClick="return true;" you will not postback so your client side event won't fire. Once I removed UseSubmitBehavior, which is the same as setting it to true, I got the functionality described in this answer. – Grant Johnson Jul 21 '22 at 19:49
8

Sure. If you use return false within your OnClientClick it will prevent any navigation from happening. So you're code would look like:

<asp:LinkButton runat="server" OnClientClick="if(!ValidatePage()) { return false;}" />
Steven V
  • 16,357
  • 3
  • 63
  • 76
  • @oshirowanen I honestly don't remember exactly why you explicitly why you have to put `return false` in the `OnClientClick`. If I recall, it has to do with the encapsulation ASP.NET does around your code within the `OnClientClick` when it renders the actual HTML and Javascript. – Steven V Oct 02 '13 at 15:58
2

Yes you can, In onclientClick function call use preventDefault()

function onclientClickFun(e)
{
  if(!IsValidationSuccess)
 {
   e.preventDefault();
 }

}

OR

function onclientClickFun(e)
{
  if(!IsValidationSuccess)
 {
   return false;
 }

}
Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
1

I came across this issue too. Did not like to have to put the OnClientClick=return false on every linkbutton. With a simple page it just easier to use an anchor and avoid asp filling the href in for you.

However this is not always possible. So a Simple conclusion is just to inherit the LinkButton and add a variable like AutoPostBack. if false then just override the output with the html or add the OnClientClick in. I dont really like inline tags.

namespace My.WebControls {
    [ToolboxData("<{0}:LinkButton runat=server ID=btn></{0}:LinkButton>"), ParseChildren(true), ToolboxItem(true)]
    public class LinkButton : System.Web.UI.WebControls.LinkButton {

         private bool _postback = true;
         [Bindable(true), Category("Behavior"), DefaultValue(true), Description("Gets or Sets the postback click behavior")]
         public bool AutoPostBack { get { return _postback; } set { _postback = value; } }


         protected override void Render(System.Web.UI.HtmlTextWriter writer) {
             if(!AutoPostBack){
                 this.OnClientClick = "return false";
             }
             base.Render(writer);
         }
    }
}

Many attributes should need to be handled in a ViewState but in this case I think we are good;

Mike
  • 623
  • 6
  • 26
1

In the server page create the button:

var button1 = new Button();  
button1.ServerClick += new EventHandler(button1_ServerClick);
button1.OnClientClick = SetJsForSaveBtn();
button1.Attributes.Add("UseSubmitBehavior", "false");
panel.Controls.Add(button1 );

//Contains the server code

private void saveBtn_ServerClick(object sender, EventArgs e)
{
   //do something if ClientClick returns true
}

//Contains the JS code for the page

LiteralControl js = new LiteralControl();
panel.Controls.Add(js);
js.Text =@"<script type='text/javascript'> 
$(document).ready(function(){
 function CheckValidationOnClient(){
   if(!ValidatePage()){
    return false;
   }
   else{
    return true;
   }
 };
});
</script>   ";

private string SetJsForSaveBtn()
{
  var jsfunc = @" return CheckValidationOnClient()";
  return jsfunc ;
}
chri3g91
  • 1,196
  • 14
  • 16