Problem:
I have a list that consist of two tabs. When I submit a form and the page reloads I would like to track which tab the user was last on in order to activate it again.
HTML code:
<ul id="myTab" class="nav nav-tabs">
<li class="active">
<a href="#participants" data-toggle="tab">Participants</a>
</li>
<li>
<a href="#gradevalues" data-toggle="tab">Criteria</a>
</li>
</ul>
PHP code:
The PHP will generate a variable $subtabname that contains “participants” or “gradevalues”.
Scenario:
If I am on #gradevalues and submit the form, the variable $subtabname will contain “gradevalues”. I would jQuery like to remove “active” class from #participants and add it instead to the li for #gradevalues.
Question:
How would I with jQuery do to find the element using this PHP variable and move to it’s parent li to remove/add an “active” class?
[UPDATE]: Non-optimal working jQuery code
$( "#myTab li.active" ).removeClass("active");
$( "#myTab a[href=#'.$subtabname.']" ).parent("li").addClass("active");
In the PHP file:
In the jQuery file:
I’ve optimized your code a bit:
I pass the class name as a string to avoid code repetition (in your code, the class name string repeats three times). I also reduced the number of DOM queries from two to one.
Btw, if you need the reference to the #myTab element in some other parts of your code, cache it in a variable, and use that variable instead of doing multiple DOM queries for that same element.