Showing posts with label OnClick. Show all posts
Showing posts with label OnClick. Show all posts

Tuesday, April 10, 2012

ASP:Button OnClientClick and OnClick not working

Sometimes you face really strange scenarios in Development, I faced a very strange issue about Event handlers while development of simple application. It proves that its not always Developers fault for coding defects.

I was creating a Search module in our application where I want call OnClientClick event for validation and if the validation returns true then perform search on DataSource using OnClick event of the Search button.

I have created a JavaScript function for validation and called that method in OnClientClick event
function ValidateSearch()
{
    var flag = true;
    // JavaScript code for validation
    return flag;
}
following is the ASP.Net code for Search button.
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="ValidateSearch()" />

With above code it should call ValidateSearch() method first on click of Search button and based on the return value, it should call the Server-Side event.

Everything is OK, but above code didn't work, [Don't give up in such cases] 
I tried some other alternative like...

1) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="javascript:return ValidateSearch();" />

2) <asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="return ValidateSearch();" />

but still no Success.

Solution:
We have to explicitly return the result after checking the functions return value. 

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" OnClick="keywordSearch_Click" OnClientClick="if (!ValidateSearch()) { return false;};" />

Hope this helps you.