Krtl
Krtl

Reputation: 1

getElementById() ? Remembering the last active tab after a submit / refresh

I have a really annoying problem, that I can't solve since a few days of trying and googlin' around.

I have some tabs in my form.
When I am in the third tab (3 / 3) and I hit submit to update my form I always get to the first tab.
I want to stay at the active tab.

Here is my jQuery

$(document).ready(function () {
    /***** intra - Tabs *****/
    $('.intra-tab-content').hide();
    $('.intra-tab-content:first').show();
    $('.intra-tab').click(function () {
        var tabContentId = '#' + $(this).attr('name');
        $('.intra-tab').attr('class', 'intra-tab');
        $(this).attr('class', 'intra-tab intra-tab-bar-actual-tab');
        $('.intra-tab-content').hide();
        $(tabContentId).show();
    });
});

And here is my HTML

<div class="intra-tab-bar">
<ul>
    <li><a href="#" name="tab0" class="intra-tab intra-tab-bar-actual-tab">foo</a>

    </li>
    <li><a href="#" name="tab1" class="intra-tab intra-tab-bar-actual-tab">bar</a>

    </li>
    <li><a href="#" name="tab2" class="intra-tab intra-tab-bar-actual-tab">foobar</a>

    </li>
</ul>

Would be great if someone could help me..
Thanks in advance
Krtl

Upvotes: 0

Views: 501

Answers (2)

Shouvik
Shouvik

Reputation: 11740

There are a bunch of ways to tackle this issue. The most elegant way is already suggested by Florian, instead of using the browser submit functionality, define your own submit behaviour using ajax which prevents a page load.

Alternatively:

  1. If you can utilize local storage i.e., you client is a HTML5 based browser, what you can do is set a flag for which tab you would like to load the page. Clear the flag after it is used.
  2. Send back an extra parameter to the server with the final tab the user was on. This way when you reload you can have the tab id sent back from the server and reload your page. This combined with ajax will allow you to change tabs on the client to specify server errors too!

Though this answer is just for more ways to solve the problem. For something that just works, go for ajax!

Upvotes: 0

Florian Gl
Florian Gl

Reputation: 6014

After you hit submit, the default behavior of your page is to reload, thus resulting your page to get into initial state (tab 1 selected).

So there are two opportunities:

  • You can save the selected tab on your server (e.g. in a session) and load it in jQuery's ready callback

  • Don't let your page use the default behavior, instead calling your custom submit callback function and stop propagation:

$("#submit-form").submit(function () { var formData = $(this).serialize(); //jQuery function to get the forms values $.ajax({ url: "url", //forms url type: "POST/PUT/GET/DELETE", //default: get data: formData, success: function(data) { //success callback } }); return false; //stops propagation });

Upvotes: 1

Related Questions