ASP.NET OnClientClick="return false;" doesn't work

Viewed 81770

I just want to add some client side (JQuery Javascript) validation in a web user control. I put an OnClientClick handler and the function gets called. BUT, even if I return "false", the OnClick method always get fired. What am I doing wrong ?

I'm with VS 2010, targeting the 4.0 framework with JQuery 1.4.2. and JQuery UI 1.8.4.

Here's a sample code :

<td style="text-align:right"><asp:Button ID="btnAddSave" OnClientClick="return ValidateMail();" OnClick="btnAddSave_Click" runat="server" Text="Submit" /></td>

Script method :

function ValidateMail() {
alert("Bouton clicked");
return false;

}

If I put a breakpoint in the Page_Load event, I see that I get in and the btnAddSave_Click event is also executed.

8 Answers

oddly enough this worked for me:

OnClientClick="javascript:SubmitTableData(); return CanSubmit();"

set the return value submit with the first function call:

function CanSubmit() {    
    return submit;
}

Hope this helps someone.

Try to set a hidden button with that OnClick attribute like:

<asp:Button ID="Button6" runat="server" onclick="btnAddSave_Click" Text="Button" style="visibility: hidden;" />

remove the OnClick attribute from the button and return false in the OnClientClick attribute like:

<td style="text-align:right"><asp:Button ID="btnAddSave" OnClientClick=" ValidateMail(); return false;"  runat="server" Text="Submit" /></td>

click the hidden button to fire the OnClick method depend on condition in script method:

function ValidateMail() {
 if(true)
 {
    $('#Button6').click();
 }
 else
 {
    //do something
 }
}
Related