Travis Michael Heller
Travis Michael Heller

Reputation: 1248

how to remove a specific item from an array based on what item you click using javascript

I want to be able to click on a list item(which is made from the items of the array) and remove it permanently from the array. I am able to remove it when clicked using remove(), but when I add another item to the array the item shows back, plus the new item i just added.

JSFIDDLE account: http://jsfiddle.net/trav5567/3s64o1ta/1/

Javascript

      function testArray(){
       var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];
       function initArray(){
        loopArray();
       }initArray();
       function myFruit(){
         $('#addFruit').on('click', function(e) {
          e.preventDefault();
          var flag = true;
          var val = $('#fruitAdd').val();
          for(var i = 0 ; i < Fruit.length ; i ++){
            if(Fruit[i] == val){
              flag = false;
              console.log('already entered this item');
             }        
           }
           if(flag){
            Fruit.push(val);
            loopArray();
           }
         });
         }myFruit();
         function loopArray(){
           var fruitList = $('ul.fruit');
           var arrayContainer = $('.arrayContainer');
           fruitList.empty();
           for(var i = 0; i< Fruit.length; i++){
             fruitList.append('<li>'+Fruit[i]+'</li>');
           }
          }
         function removeItem(){
            var itemClicked = $('ul.fruit li');
            itemClicked.on('click', function(){
               $(this).remove();
            });
         }removeItem();
       }testArray();

Upvotes: 0

Views: 79

Answers (1)

Chakravarthy S M
Chakravarthy S M

Reputation: 618

You are not removing item from array when clicked, you are just removing the li tag which contains element when clicked, for to remove element from array also when clicked on item's li, you have to use splice method to remove element from array as

    var itemClicked = $('ul.fruit li');
       itemClicked.on('click', function () {
       $(this).remove();
       var item = $(this).text();
       var index = Fruit.indexOf(item);
      Fruit.splice(index,1);
   });

Check the Working Fiddle Here

Upvotes: 1

Related Questions