remove appended data with button click id by id

Viewed 52

I append a dynamic button and want when I click button Related data will be remove

async function DataShow()
{
for (i = 0; i < localStorage.length; i++)
     {
      x = localStorage.key(i);
      if (x !='debugbar-time-new' && x !='debugbar-time' && x!='__mycart')
      {
        item = await JSON.parse(localStorage.getItem(x))
        $("#table_data").append('<tr> <td>'+item['_id']+'</td> <td>'+item['title']+'</td><td><button class="btn btn-primary remove" value="'+item['_id']+'">remove</button></td></tr>')
      }
    }
} 

there is my remove functionality

$( "#table_data" ).on('click','.remove',function(){
var item_id = $('#table_data button').val()
window.localStorage.removeItem(item_id);
  });

Problem is when I click button Button always fetch last element id I also see with inspect element all button have it's own id I also try $('this').val() but it not working

1 Answers

You can use the this keyword within the event handler to refer to the element which raised the event. In your case you can use this to get the value property:

$("#table_data").on('click', '.remove', function() {
  var item_id = this.value;
  window.localStorage.removeItem(item_id);
});
Related