0

Im display some data into table and for each row there is Delete button, when button clicked it should Delete item in array which is stored in localStorage by passing id and than Assign it back to LocalStorage.

HTML:

<table>
     <tbody id="ResultProduct">
       <tr class="RMAJS">
          <td><input type="text" id="item1" name="itemName" value="Computer" /></td>
          <td><a data-localstorage-id='ae90ac1a-64c4-49a7-b588-ae6b69a37d47' class="deletebtn">Delete</a></td>
       </tr>
       <tr class="RMAJS">
         <td><input type="text" id="item2" name="itemName" value="Mobile" /></td>
         <td><a data-localstorage-id='6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b' class="deletebtn">Delete</a></td>
       </tr>
    </tbody>
</table>

LocalStorage :

["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"]

0: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
1: "6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"

JavaScript :

$('#ResultProduct').on('click', '.deletebtn', function (e) {
    var targetElement = $(e.target);
    var getID = $(targetElement).attr("data-localstorage-id");
    var getLocalStorage = JSON.parse(localStorage.getItem("users"));

    for (var i = 0; i < getLocalStorage.length; i++) {
        var Val = getLocalStorage[i]

        //Here is my problem for example i want to delete this item 
       //"6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b" from array 
       //How can i do that ??

       localStorage.setItem('users', JSON.stringify(??)); //Assign it back to LocalStorage.
    }

    $(targetElement).closest("tr.RMAJS").remove();
})

3
  • you can splice() it to remove an index entirely Commented Dec 19, 2019 at 21:41
  • getLocalStorage = getLocalStorage.filter(item => item !== getID)? Commented Dec 19, 2019 at 21:42
  • @dandavis so it will be like this : Val.slice(getID, 1); ?? Commented Dec 19, 2019 at 21:45

1 Answer 1

1
$('#ResultProduct').on('click', '.deletebtn', function (e) {
    var targetElement = $(e.target);
    var getID = $(targetElement).attr("data-localstorage-id");

    var getLocalStorage = JSON.parse(localStorage.getItem('users'));
    getLocalStorage = getLocalStorage.filter(e => e !== getID);
    localStorage.setItem('users', JSON.stringify(getLocalStorage));

    $(targetElement).closest("tr.RMAJS").remove();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.