Here i am creating a shopping list, i have a text box to enter the item and submit button to add the item to array. on submit the item gets pushed to array and the the list will get updated.what i am trying to do is when i click on the any of the listed item i should be able to get its id, but i couldn't get it.how can i resolve this?
here is what i have done:
'use strict';
(function() {
var itemslist = [];
$('#addList').click(function(e) {
var item = $('#itemname').val();
if (item == '') {
alert('Cannot be empty!')
return false;
} else {
e.preventDefault();
itemslist.push(item);
update();
}
})
var update = function() {
$('#shopList').empty();
itemslist.forEach(function(value, index) {
$('#shopList').append("<section id='" + index + "' class='items-list'>" + value + "</section>") //list-item gets appended after the successful push of item to array
})
}
$('.items-list').click(function() {
console.log(this.id); //unable to get the clicked element id
})
})(window);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<form method="post" name="listform">
<input id="itemname" type="text" value="" name="item" placeholder="Ex: butter and milk" required>
<button class="btn btn-peace" id="addList"><i class="fa fa-shopping-cart" aria-hidden="true"></i> Add to List</button>
</form>
</div>
<div id="shopList">
</div>