Tuesday, August 7, 2012

jQuery UI Tabs - Maintain same tab after postback

I think this is a common issue if you are using jQuery UI Tabs. The issue is when you click a submit button inside a any tab other than the first tab, you will be landed on the first tab after postback. It can really be a trouble if you want to stay on the same tab after postback.
Here is a simple workaround to solve that problem.
  • Add a hidden field inside the tabs div.
    <div id="tabs">
        <asp:HiddenField ID="tab_index" Value="0" runat="server" />
        <ul>
            <li><a href="#tabs-1">Tab 1</a></li>
            <li><a href="#tabs-2">Tab 2</a></li>
            <li><a href="#tabs-3">Tab 3</a></li>
        </ul>

        <div id="tabs-1">
            <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"/>
        </div>

        <div id="tabs-2">
            <asp:Button ID="Button2" runat="server" Text="Submit" OnClick="Button2_Click"/>
        </div>

        <div id="tabs-3">
            <asp:Button ID="Button3" runat="server" Text="Submit" OnClick="Button3_Click"/>
        </div>
    </div>
  • Add this script to your master page.
    <script type="text/javascript">
        $(document).ready(function () {
            var iSelectedTab = $(this).find("input[id*='tab_index']").val();
            if (iSelectedTab == null)
                iSelectedTab = 0;
            $('[id$=tabs]').tabs({ selected: iSelectedTab });
        });
    </script>
  • In your code behind file, set the current tab in the postback event.
protected void Button1_Click(object sender, EventArgs e)
{
    tab_index.Value = "0";
}

protected void Button2_Click(object sender, EventArgs e)
{
    tab_index.Value = "1";
}

protected void Button3_Click(object sender, EventArgs e)
{
    tab_index.Value = "2";
}
Hope this helps.

Happy Coding.

Regards,
Jaliya