I'm building a UI where a user can select from a list, include the selection in an array and then display the array in another list. I'm very close. However, every time I add an item to the list it repeats items.
How do I clear the list before it builds from the array again.
You can see how it works and my code here:
$(document).ready(function(){
var a = [];
$(".btn").click(function(){
a.push($(this).next("span").text());
$(this).closest("li").hide();
$( "#s" ).text( a.join( " " ) );
$.each(a, function(i){
var cList = $('ul.mylist');
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('<a/>')
.addClass('ui-all')
.text(a[i])
.appendTo(li);
});
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Selector</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<h2>List of Options</h2>
<ul>
<li><button class="btn">Select</button><span>One</span></li>
<li><button class="btn">Select</button><span>Two</span></li>
<li><button class="btn">Select</button><span>Three</span></li>
<li><button class="btn">Select</button><span>Four</span></li>
</ul>
<h2>List of Selections</h2>
<ul class="mylist">
</ul>
<h2>Array</h2>
<div>Array of Selected Items to Send to DB:</div>
<span ID="s"></span>
</body>
</html>