How to call onclientclick after onclick

Anton Belev picture Anton Belev · Jul 3, 2013 · Viewed 7k times · Source

I've got this button

<asp:Button runat="server" ID="btnReviewDocs" CssClass="btnReviewDocs" data-theme="b"
                Text="Review Documents" OnClick="btnReviewDocs_Click" OnClientClick="clickHyperlink();"/>

And in 'OnClick' event I'm assembling an URL that I need to set to asp:Hyperlink and at the end of the 'OnClick' I'm setting this URL to the 'NavigateURL' propery of the 'asp:Hyperlink'. Once the 'asp:Hyperlink' has the correct URL I need to call the 'clickHyperlink()' function.

function clickHyperlink() {
    var href = $('#hlnkID').attr('href');
    if (typeof href !== "undefined") {
        $.mobile.showPageLoadingMsg();
        window.location.href = href;
    }
}

But the 'OnClientClick' event is executed always before the 'OnClick'. Any suggestions for a workaround?

I'm doing all this stuff, because I've got problems with JQuery Mobile and 'Response.Redirect(url);' is changing the page, but not the URL.

Answer

Alex Filipovici picture Alex Filipovici · Jul 3, 2013

I believe that you don't really need to involve the Hyperlink control in the JS part. Modify your JS function and remove the OnClientClick attribute from the btnReviewDocs button:

<script type="text/javascript">
    function clickHyperlink(href) {
        $.mobile.showPageLoadingMsg();
        window.location.href = href;
    }
</script>

On the server, in the btnReviewDocs_Click method:

protected void btnReviewDocs_Click(object sender, EventArgs e)
{
    // TODO: set the url, maybe append some params to the 
    // hlnkID.NavigateUrl value
    var url = "http://stackoverflow.com/";
    ClientScript.RegisterStartupScript(Page.GetType(), 
        "clickHyperlink",
        "clickHyperlink('" + url + "');",
        true);
}