CyberJunkie
CyberJunkie

Reputation: 22674

Jquery remove element from array

This should be fun to solve :)

In a text field I have the value Apple,Peach,Banana.

Using Jquery I created an array from that CSV.

In HTML I have a list of the fruits with a "remove" option next to each one. When I click "remove" I want to remove the corresponding fruit from the list and the text field.

I'm missing one function that will remove fruits from the array. What function should I use?

http://jsfiddle.net/BXWqK/19/

Upvotes: 12

Views: 41896

Answers (3)

Doug
Doug

Reputation: 35136

The accepted solution is correct, but it doesn't mention that you shouldn't use indexOf to get the fruit_index to remove, because IndexOf not Supported in IE8 Browser

You should use:

fruits_array.splice($.inArray('Peach', fruits_array), 1);

Upvotes: 2

kennebec
kennebec

Reputation: 104780

    var A=['Apple','Peach','Banana'];

    A.splice(1,1)

// removes 1 item starting at index[1] 
// returns ['Peach'];

Upvotes: 6

Tim
Tim

Reputation: 5822

You should use JavaScript Splice

fruits_array.splice(fruit_index,1);

You also need to change:

$('#fruits').val(skills_array.join(',')); to $('#fruits').val(fruits_array.join(','));

Upvotes: 25

Related Questions