I'm building a UI where a user can click on an item in an 'Options' list and add it to a 'Selected' list.
The items on the 'Selected' list have a remove button to send it back to the 'Options' list. I just can't get the remove button to work. I have limited the action of the remove button to a simple alert for troubleshooting purposes.
Can anyone see what I'm doing wrong?
PS. My question has been marked as a duplicate: Event binding on dynamically created elements? I have read that question and I'm trying to apply it. I'm looking for specific help on what I'm doing wrong in my code.
$(document).ready(function(){
var a = [];
$(".remove").click(function(){
alert("Remove Clicked");
});
$(".select").click(function(){
var cList = $('ul.mylist');
$('ul.mylist').empty();
$('ui-menu-item').empty();
a.push($(this).next("span").text());
$(this).closest("li").hide();
$( "#s" ).text( a.join( " " ));
$.each(a, function(i){
var li = $('<li/>')
.addClass('ui-menu-item-'+a[i])
.attr('role', 'menuitem')
.appendTo(cList);
var aaa = $('<a/>')
.addClass('ui-all')
.text(a[i])
.appendTo(li);
var $input = $('<button class="remove">Remove</button>');
$input.prependTo($("li.ui-menu-item-"+a[i]));
});
});
});
<!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="select">Select</button><span>One</span></li>
<li><button class="select">Select</button><span>Two</span></li>
<li><button class="select">Select</button><span>Three</span></li>
<li><button class="select">Select</button><span>Four</span></li>
</ul>
<h2>List of Selections</h2>
<ul class="mylist">
</ul>
<h3>Array of Selected Items to Sent to DB:</h3>
<span ID="s"></span>
</body>
</html>