Introduction
Sometimes, we may need to create/develop some logic in jQuery to add/delete tabs. We will see how easily we can do that using jQuery Tabs and Bootstrap Tabs. It has always been fun to play with jQuery, which is very user-friendly. So let's get started.
Ingredients
- jQuery (min version of jQuery and UI jQuery JS)
- jQuery UI (minified version of jQuery UI JS)
- jQuery UI CSS
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
What Will We Do?
We will perform some basic CRUD operations on a jQuery Tab along with the sorting tab order.
- Add a Dynamic Tab
- Delete the Tab
- Sort Tabs with the Sort Order
HTML
<div class="mainbox">
<h1>
<b style="color:#9ee0ff;">jQuery Tab</b> Add, Delete and Sorting Example
</h1>
<div id="tabs">
<ul>
<li id="1"><a href="#tab-1">Default</a></li>
</ul>
<div id="tab-1">
<p>
Default Tab Content
</p>
</div>
</div>
<p>
<button id="showDialog" class="ui-button ui-widget ui-corner-all">+ Add Tab</button>
<button id="removeTabs" title="Click to Remove Active Tab" class="ui-button ui-widget ui-corner-all">x Remove Tab</button>
<button id="showSortable" class="ui-button ui-widget ui-corner-all">Get Sort Order</button>
</p>
<p style="margin-top:50px;">
By Darshan Shah <a href="https://www.c-sharpcorner.com/members/darshan-shah" target="_blank">https://www.c-sharpcorner.com/members/darshan-shah</a>
</p>
</div>
<div id="divDialog" style="display:none;padding:10px;">
<div>
<input type="text" required class="txt" placeholder="Enter new tab name" />
</div>
<div>
<button type="button" id="addTabs" class="ui-button ui-widget ui-corner-all">Submit</button>
</div>
</div>
User Defined CSS
.mainbox {
width: 70%;
margin: 0 auto;
margin-top: 30px;
font-family: Arial;
}
.mainbox h1 {
background-color: #808080;
color: white;
font-size: 14px;
padding: 10px;
text-align: center;
border-radius: 5px;
}
.mainbox p {
text-align: center;
}
.ui-widget-overlay.custom-overlay {
background-color: black;
background-image: none;
opacity: 0.7;
z-index: 1040;
}
.txt {
border: solid 1px #eee;
padding: 5px;
outline: none;
margin-bottom: 10px;
}
.txt:focus {
border: solid 1px #0094ff;
}
Scripts
// Make tab UI activated using below script
var $tabs = $('#tabs').tabs();
// Open jQuery Dialog to open modal popup - here we ask for tab name from user
$("#showDialog").click(function () {
$("#divDialog input").val("").focus();
$("#divDialog").dialog({
title: 'New Tab', modal: true, open: function () {
$('.ui-widget-overlay').addClass('custom-overlay');
}
});
});
// Adding new Tab on button click
$("#addTabs").click(function () {
// Checking textbox is empty or not
if ($.trim($("#divDialog input").val()) == "") {
$("#divDialog input").val("").focus();
}
else {
// Checking tab name already exist or not
var tabNameExists = false;
$('#tabs ul li a').each(function (i) {
if ($.trim(this.text.toLowerCase()) == $.trim($("#divDialog input").val().toLowerCase())) {
tabNameExists = true;
}
});
// code to insert new tab here if tab name does not exist
if (!tabNameExists) {
// Here we are getting max id so that we can assing new id to new tab
var maxid = 0;
$('#tabs ul li').each(function () {
var value = parseInt($(this).attr('id'));
maxid = (value > maxid) ? value : maxid;
});
var newid = maxid + 1;
// Adding new "<li>" with anchor tag
$("#tabs ul").append(
"<li id='" + newid + "'><a href='#tab-" + newid + "'>" + $("#divDialog input").val() + "</a></li>"
);
// Adding Div for content for the above "li" tag
$("#tabs").append(
"<div style='display:none;' id='tab-" + newid + "'><p>Content for Tab: " + $("#divDialog input").val() + "</p></div>"
);
// Refreshing the tab as we have just added new tab
$("#tabs").tabs("refresh");
// Make added tab active
$("#tabs").find('li a[href="#tab-' + newid + '"]').trigger("click");
$("#divDialog").dialog("close");
}
else {
// Showing message if tab name already exist
alert("Sorry! Tab name already exist");
$("#divDialog input").focus();
}
}
});
// Remove Active Tab on button click
$("#removeTabs").click(function () {
// Confirm from user that he/she sure wants to delete this active tab
if (window.confirm("Are you sure want to delete this active Tab?")) {
// Find name of Tab by attribute id
var tabIndex = $("#tabs .ui-tabs-panel:visible").attr("id");
// Removing Li and as well as content Div for the specific Tab
$("#tabs").find(".ui-tabs-nav li a[href='#" + tabIndex + "']").parent().remove();
$("#tabs").find("div[id=" + tabIndex + "]").remove();
// One removing process done we refresh the tab again
$("#tabs").tabs("refresh");
}
});
// Here we are making jQuery Tabs (li tag) Sortable
$(function () {
$("#tabs ul").sortable({ containment: "#tabs ul" });
$("#tabs ul").disableSelection();
});
// ************ 2 ways to getting sorting order *************
// We can get sort order directly once you done sort by drag & drop
$("#tabs ul").bind("sortupdate", function (event, ui) {
event.stopPropagation();
alert($("#tabs ul").sortable('toArray'));
});
// Another way of getting current sort order of tab using below script
$("#showSortable").click(function () {
alert($("#tabs ul").sortable('toArray'));
});
Here, we have added all the required source code to make it work.
Notes
- This is a pure jQuery-based example of jQuery CRUD operation for Tab.
- Here, I have tried to make the code as much as simple and clean.
- There are actually many ways to get certain operations done in jQuery but I have chosen some basic and easy ways to understand scripts.
Screens
This is the default screen - we are showing one tab already created here.
The popup for adding a new tab will be shown upon a click of the Add Tab button.
Here we can see a new tab named "Test Tab" has been added successfully.
The Remove Tab button will delete the active or selected tab from the tab list.
We ask for confirmation from the user whether we would like to go ahead with this delete action.
On approval, we can see a tab named "Profile" has been deleted successfully.
Here, I have given another feature to sort the tab like the below screen. Just drag & drop.
Once drag & drop is done, it will show you the latest tab order. (The ID attribute is being used here).
Another option to get the latest tab order by clicking the button named "Get Sort Order"
I hope you liked this article and as a reference, I have attached a single file source code with this article.
Many thanks for reading!