Travis Michael Heller
Travis Michael Heller

Reputation: 1248

As soon as i add an item to my array i am unable to delete an item from my array

i can delete items from my array as long as I don't try and add an item to the array first. otherwise i am unable to delete items from my array. i know this sounds confusing so i added a jsfiddle to show. JSFiddle: http://jsfiddle.net/trav5567/3s64o1ta/5/

Any help would be great:)

javascript

function testArray() {
    var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];
    var errorMsg = $('.errorMsg');
  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;
                errorMsg.find('p').removeClass();
                errorMsg.find('p').addClass('error');
                errorMsg.find('p').text('already entered this item');
            }
        }
        if (flag) {
          Fruit.push(val);
          loopArray();
          errorMsg.find('p').removeClass();
          errorMsg.find('p').addClass('correct');
          errorMsg.find('p').text('Item has been added');

        }
    });
  }
  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>');
     }
  }

  var itemClicked = $('ul.fruit li');
  itemClicked.on('click', function () {
    $(this).remove();
    var item = $(this).text();
    var index = Fruit.indexOf(item);
    Fruit.splice(index,1);
    errorMsg.find('p').removeClass();
    errorMsg.find('p').text('Item has been removed');
 });


 }
 testArray();

Upvotes: 1

Views: 62

Answers (2)

Santhanakumar
Santhanakumar

Reputation: 382

change the

itemClicked.on('click', function () { 

to

$('body').on('click', 'ul.fruit li', function () {

Explanation:

The click event should attached to the body.Because all the li's are loaded after document loaded.

Upvotes: 0

dfsq
dfsq

Reputation: 193291

You have to use event delegation if you want to handle events on dynamically added elements:

$('ul.fruit').on('click', 'li', function () {
    $(this).remove();
    var item = $(this).text();
    var index = Fruit.indexOf(item);
    Fruit.splice(index,1);
    errorMsg.find('p').removeClass();
    errorMsg.find('p').text('Item has been removed');
});

The idea is that you bind one event handler on the parent element (ul.fruit) and it will handle all click event bubbling up from the child nodes.

Upvotes: 3

Related Questions