Reputation: 2281
I am creating a web application and I want to use the Tabs widget to replicate the tab functionality you find in most web browsers. I want the user to be able: to move (sort) the tabs around, create tabs dynamically, close tabs dynamically.
I am having a problem deleting tabs that have been moved around.
Lets say there are three tabs named:
one, two and three.
If I move "one" so the tabs are like:
two, three and one
When I delete "one", which has an index of 2, tab "three" is deleted. So the tabs are now:
two, and one.
I have tested many different scenarios and it appears to me when I remove a tab, JQueryUI removes the wrong tab that initially had the index value, and not the tab that currently has the index value.
Upvotes: 7
Views: 22564
Reputation: 3181
Updated in June 2023
The below function started using Matthew's answer above.
I modified it for more flexibility as some of us will have different #IDs for our elements.
function removeTab(tabsObj,tabId) {
let returnVal = false;
if($(tabId).length && $( tabId ).remove()){
$(tabsObj).tabs( "refresh" );
let hrefStr = "a[href='" + tabId + "']"
if($( hrefStr ).closest("li").remove()){
returnVal = true;
}
}
return returnVal;
}
It also returns a false if the tab doesn't exist and true on success
Upvotes: 1
Reputation: 13556
Annoyingly remove is no longer in the jQueryUI tab API. You must now remove the HTML that renders the tab and panel itself and refresh the tabs:
function removeTab(tabId) {
var tabIdStr = "#tabs-" + tabId
// Remove the panel
$( tabIdStr ).remove();
// Refresh the tabs widget
tabs.tabs( "refresh" );
// Remove the tab
var hrefStr = "a[href='" + tabIdStr + "']"
$( hrefStr ).closest("li").remove()
}
https://forum.jquery.com/topic/dynamically-remove-tab
Upvotes: 4
Reputation: 19
I temporarily solved the problem this way:
.click(function(e) {
$tab.tabs('remove',$tab.tabs('option','selected'));
});
Upvotes: 1
Reputation: 4901
You're right that the tabs keep their old index values when you reorder them, leading to unexpected behavior when you try to remove one. You can force it to update the indexes by reinitializing the tabs before deleting, like so:
$('#tabs').tabs('destroy').tabs();
$('#tabs').tabs('remove', 2);
This works because the indexes are generated when the tabs are set up based on the positions of the li
elements in the DOM. When you move the tabs around, the li
positions are updated in the DOM, even if their index values don't change in the Tabs plugin.
Of course, if you have a very complicated setup, this might have negative performance implications, in which case you could figure out some other way to update the tab indexes, or you could maintain an array that maps the original indexes to the current indexes.
Upvotes: 7