Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping onclick from firing when onclientclick is false?

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?

like image 323
oshirowanen Avatar asked Oct 02 '13 14:10

oshirowanen


2 Answers

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> 
like image 94
Win Avatar answered Sep 18 '22 23:09

Win


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;}" /> 
like image 43
Steven V Avatar answered Sep 19 '22 23:09

Steven V