Sometimes one wishes to have a javascript, attached to a button/link/what have you, on a page that will, in some cases, cancel the postback/form submission. All one needs to do is simply set the control onClick (or OnClientClick, in the case of ASP.NET) to

return SomeFunction();

and then return true or false in the function, as appropriate.

Do not forget the “return” before your function name, else the postback/submission will always occur, regardless of what you return from the function. A quick example is always handy, and┬áhere it is.┬áThe page is from a recent project of ours, and services the purpose of changing user’s details, specifically the password. There are two text inputs – textboxes – on the page for a new password and confirming the new password (not shown here):

Web page (C#)

<asp:Button ID=”Button_SaveUser” runat=”server” Text=”Save user” onclick=”Button_SaveUser_Click” OnClientClick=”return SaveUserClicked();” />

Web page (pure HTML)

<input id=”Button_SaveUser” type=”button” value=”Save user” onclick=”return SaveUserClicked();” />

Javascript

function SaveUserClicked() {
if(DoPasswordsMatch()) {
return true;
}
else {
alert(“Both passwords do not match, please retype them!”);
return false;
}
}

The DoPasswordsMatch() function simply compares the two textboxes’ text and returns true if they match.

Easy when you know how, isn’t it…