I'm creating a dynamic page using clone property.
The problem occurs when I create say 4 Assured elements and when I close the first Assured (i.e) Assured 1, the close if statement occurs multiple times based on the nth-element value (hopefully).
I would like only one loop to occur such that the id-- occurs only once...
$(document).ready(function() {
var id = 1;
var assured = document.getElementById('assuredconb');
$('.add-contact').click(function(e) {
e.preventDefault();
if (id < 5) {
$(this).closest('li').before('<li><a data-toggle="tab" href="#assured' + id + '">New assured ' + id + '</a><span class="fas fa-times-circle close" id="close' + id + '"></span></li>');
var clone = assured.cloneNode(true);
clone.id = "assured" + id;
$('.tab-content').append(clone);
id++;
}
$('.close').click(function() {
id--;
var anchor = $(this).siblings('a');
$(anchor.attr('href')).remove();
$(this).parent().remove();
$(".nav-tabs li").children('a').first().click();
alert(id);
});
});
});
.close {
color: red;
opacity: 0.8;
position: absolute;
right: 5%;
top: 25%;
}
.nav-tabs>li>a {
width: 175px;
text-align: center;
}
.add-contact {
width: 50px !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://use.fontawesome.com/releases/v5.0.2/css/all.css" rel="stylesheet">
<body>
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#assuredconx">Mr.X</a></li>
<li><a data-toggle="tab" href="#assuredconb">Mr.Boy</a></li>
<li><a data-toggle="tab" class="add-contact" style="cursor:pointer"><i class="fas fa-plus"></i></a></li>
</ul>
<div class="tab-content">
<div id="assuredconx" class="container-fluid tab-pane fade in active">#1</div>
<div id="assuredconb" class="container-fluid tab-pane fade">#2</div>
</div>