Morpheus
Morpheus

Reputation: 997

jquery removing items from the array doesn't work

I was able to find answer that I changed a bit and tried to make it work but without success.

I would like to remove item when user press x button:

Part of JS code:

    animals = temp;
    for (var i = 0; i < animals.length; i++) {
        newOutput += '<p>' + animals[i] 
                   + '<input type="number" class="animals-input pull-right text-right" value="0" />' 
                   + '<a href="#" onClick="deleteItem(' + animals[i] 
                   + ')" class="pull-right delete-item">x</a></p>';
    };
    $('.animals-input').innerHTML = newOutput;

full js fiddle code

Any ideas?

Thanks.

Upvotes: 0

Views: 35

Answers (1)

palaѕн
palaѕн

Reputation: 73926

You can do this:

  for (var i = 0; i < animals.length; i++) {

    newOutput.push('<p>' + animals[i] + '<input type="number" class="animals-input pull-right text-right" value="0" />' + '<a href="#" onClick="deleteItem(\'' + i + '\')" class="pull-right delete-item">x</a></p>');
  };
  $('#list').html(newOutput.join(""));

Updated Demo

You need to change from this

onClick="deleteItem(' + animals[i] + ')"

to

onClick="deleteItem(\'' + i + '\')"

as in deleteItem() function you are passing the array index not the array value. Also, you need to put quotes while passing the parameter to the function, otherwise you get errors.

Upvotes: 1

Related Questions