Get value of selected LI and remove it from array

I have a list of user inputted strings, and want to be able to delete one individual item, while also removing it from the array. I am able to remove it successfully from the DOM, but not from the array.

So far I have tried to get the value of the selected LI and select the indexof that specific LI

$(document).on('click', 'button.delete', function () {
    let deletedItem = $(this).closest('li')
    let itemValue = $(this).closest('li').val()
    let index = items.indexOf(itemValue);
    if(index != -1) {
        items.splice(index, 1);
    }
    deletedItem.remove();
});

This does not delete it from my array, any ideas how it would be done?

4 thoughts on “Get value of selected LI and remove it from array”

  1. Try this

    let items = [1,2];
    
    $(document).on('click', 'button.delete', function () {
        let deletedItem = $(this).closest('li')
        let itemValue = $(this).closest('li').val() 
        let index = items.indexOf(itemValue);
        
        if(index != -1) {
          items.splice( index ,1); // <-- Do this
        }
        deletedItem.remove();
        
        console.log(items);
         
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <ol>
      <li value="1">
        <button class="delete">Delete</button>
      </li>
    
      <li value="2">
        <button class="delete">Delete</button>
      </li>
      
       <li value="3">
        <button class="delete">Delete</button>
      </li>
      <li value="4">
        <button class="delete">Delete</button>
      </li>
    </ol>
    Reply
  2. // To delete element from an array you had to keep track of the index in which the element exist. check the below example:
    
     // Create an array of strings;
        let array = ["Hello", "Boy", "Happy", "Fun"];
    
        // search for the index of item to be deleted in array
        let index = array.indexOf("Boy");
        console.log(index); // output: 1;
    
        // The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements
        array.splice(index, 1); // Return the removed item;
    
        // Check item present
        console.log(array); // output: [ 'Hello', 'Happy', 'Fun' ];
    Reply

Leave a Comment