Alan Alan - 7 months ago 44
HTML Question

Remove last item jquery

On click of a button, result appends to another div with the total increasing on each click.

When Remove Last button is clicked it removes the appended div but does not adjust the total.

I've looked all over for a function with no luck.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Remove last</title>

<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">


</head>
<body onLoad="renderTime();">
<div class="container-fluid">
<div class="row">
<div class="col-xs-4" id="printarea" >
<div id="print-container">
<div class="item"></div>
<div class="total"></div>
</div>
</div>
<div class="col-xs-8">
<ul class="final">
<li class="remove"><a href="#"><input type="submit" value="Remove Last" class="print-btn remove-item"></a></li>
<li class="remove"><a href="#"><input type="submit" value="Remove All" class="print-btn" data-corners="false" id="submit" onclick="refresh()"></a></li>
</ul>
<hr />
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="content">
<ul class="sub-menu">
<li><a href="#"><button class="menu item1">Item 1</button></a></li>
<li><a href="#"><button class="menu item2">Item 2</button></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">

//add item
$('.item1').click(function(){
$('<div class="delete">Item 1 - <span class="skill"> 840</span></div><br />').appendTo('.item');

counter();
});
$('.item2').click(function(){
$('<div class="delete">Item 2 - <span class="skill"> 910</span></div><br />').appendTo('.item');

counter();
});

//remove last item
$('.remove-item').click(function(){
$(".delete:last").remove();
});
</script>

<script type="text/javascript">
function refresh() {

setTimeout(function () {
location.reload()
}, 100);
}
</script>

<script type="text/javascript">

var counter = function() {

var total = 0;

$(".skill").each(function() {

total += +$(this).text();
});

$('.total').text('Total: ' + total);
};

</script>
</body>
</html>

Answer

You need to call counter(); method after the element is removed.

//remove last item
$('.remove-item').click(function() {
    $(".delete:last").remove();

    counter();
});
Comments