I am adding and removing jquery tabs programatically, with:
function addtab(input) {
var num_tabs = $("div#tabs ul li").length + 1;
$("div#tabs ul").append(
"<li class='test' title = '" + input + "'><a href='#tab" + num_tabs + "'>" + input + "</a><span class='ui-icon ui-icon-close' role='presentation'></span></li>"
);
$("div#tabs").append(
"<img id='tab" + num_tabs + "' src='<%=request.getContextPath()%>/Viewer_2D'; height='100%' width='100%'/>"
);
$("div#tabs").tabs("option", "active", num_tabs-1);
$("div#tabs").tabs("refresh");
}
$(function() {
$("#tabs").on( "click", "span.ui-icon-close", function() {
var panelId = $( this ).closest( "li" ).remove().attr( "aria-controls" );
$( "#" + panelId ).remove();
tabs.tabs( "refresh" );
});
});
If I add three tabs, and then remove the last tab, there is no problem when trying to add an additional tab- the id of the new tab will be 'num_tabs'. However, if I were to add three tabs, and then remove the first tab, then the tab with id=num_tabs already exists. How can I handle this? Can I renumber the tab ids after removing tabs?
You didn't mention this in your question, but I assume there isn't a need for the ID's to be sequential. What matters is that each ID is unique.
Instead of using num_tabs
to determine the number of the tab, you could simply always increment the number (do not decrement it when deleting tabs).
This can be done in multiple ways, like...
data-
syntax (see .data() to store the number of the tab as a value on the tab. By doing this, you can retrieve the number on the last tab and increment it to determine the number of the next tab.