0

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>
Milan Chheda
  • 7,851
  • 3
  • 18
  • 35
CJAY
  • 6,055
  • 16
  • 52
  • 90

1 Answers1

1
$(this).attr('id') 

should do the trick

The function isn't working as it is not bound to the dynamically created element.

To bind this, pick an element higher up in the hierarchy and then check which element is clicked. You can do this as below:

$(body).on('click','.items-list', function() {
    console.log($(this).attr('id') );
});
hairmot
  • 2,844
  • 1
  • 10
  • 23