开发者

Jquery remove element from array

开发者 https://www.devze.com 2023-03-10 13:50 出处:网络
This should be fun to solve :) In a text fiel开发者_Go百科d I have the value Apple,Peach,Banana.

This should be fun to solve :)

In a text fiel开发者_Go百科d 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/


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(','));


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

    A.splice(1,1)

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消