Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Staying on current jQuery tab across post back?

I am using jQuery tabs and an ASP.NET listview to display and edit some information. My problem is that when a user inserts a new record in one of the listview items my jQuery tabs go back to the first tab. Is there a way to keep track of which tab I am on or keep it from resting on post back?

like image 390
Abe Miessler Avatar asked Sep 15 '10 18:09

Abe Miessler


4 Answers

In ASP.NET, you can store it in a hidden field without having to use a cookie (no need for the jQuery cookie reference).

Use this:

$(function () {
    $("#tabs").tabs({ 
        activate: function() {
            var selectedTab = $('#tabs').tabs('option', 'active');
            $("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
        },
        active: <%= hdnSelectedTab.Value %>
    });
});

Then in the body, declare your hidden tab field:

<asp:HiddenField ID="hdnSelectedTab" runat="server" Value="0" />

Basically, on selection of a tab you are storing the selected tabs value in the asp hidden field. Then on show you are retrieving the value.

like image 110
Lloyd Powell Avatar answered Dec 25 '22 21:12

Lloyd Powell


With newer versions of jQuery and jQuery UI, this will be:

$(function () {
    $("#tabs").tabs({
        activate: function() {
            var selectedTab = $('#tabs').tabs('option', 'active');
            $("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
        },
        active: document.getElementById('<%= hdnSelectedTab.ClientID %>').value
    });
});

The 'selected' option is replaced by 'active'... Of course you will still need to add the hidden field:

<asp:HiddenField ID="hdnSelectedTab" runat="server" Value="0" />
like image 44
Eaglan Kurek Avatar answered Dec 25 '22 21:12

Eaglan Kurek


There's built-in support for the jQuery cookie plugin (direct download). You use it like this:

$("#tabs").tabs({
  cookie: { expires: 7 }  //1 week
});

It's not the same as maintaining across postback, but it usually provides the desired effect.

like image 31
Nick Craver Avatar answered Dec 25 '22 22:12

Nick Craver


Try this:

Add to the page :

<asp:HiddenField ID="hdnSelectedTab" runat="server" Value="0" />

Add to the script:

$(function () {
    var activeIndex = parseInt($get("hdnSelectedTab").value);
    $("#tabs").tabs({
        active: activeIndex,
        activate: function (event, ui) {
            $get("hdnSelectedTab").value = ui.newTab.index();
        }
    });
});
like image 22
Olegs Avatar answered Dec 25 '22 23:12

Olegs