Search code examples
javascriptjqueryrandomcartsplice

Splice removing random elements issue in javascript


I am trying create interactive shopping cart using jQuery, but splice issue ruined everything, because when I am delete element directly it works perfect to me, but than I am going to dynamically changes it doesn't work deleting random elements in array even after updates indexes.

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<div id="myDIV2"></div>
<div id="myDIV"></div>
<script>
 var wishlistArray = ["Item1", "Item2", "Item3", "Item4", "Item5"];

 function wishlist_show() {

     var wishlistArrayDom = "";
     jQuery.each(wishlistArray, function (i, wishlistID) { 

         wishlistArrayDom += '<div><a href="javascript:;" class="rem-from-wishlist" value="' + i + '">Remove( ' + wishlistID + ' )</a></div>';
     });

     $('#myDIV').empty();
     $('#myDIV').html(wishlistArrayDom);
     wishlist_update_rem();

     console.log('All: ' + wishlistArray.length);
     console.log('Arr: ' + wishlistArray);
 }

 function wishlist_rem(num) {
     console.log('Value: ' + $(this).attr('value'));
     console.log('All: ' + wishlistArray.length);
     console.log('Arr: ' + wishlistArray);
     $(this).parent().slideUp("slow", function () {
         console.log(wishlistArray.splice($(this).attr('value'), 1));
         wishlist_show();

     });
     $('#myDIV2').append('<br>Remove ' + wishlistArray[parseInt($(this).attr('value'))] + ' of element' + +$(this).attr('value'));
 }

 wishlist_show();

 function wishlist_update_rem() {
     $(".rem-from-wishlist").unbind("click");
     $(".rem-from-wishlist").click(wishlist_rem);
 }
</script>

Jsfiddle example

UPDATE: Solved by myself, thanks to all, stackoverflow is best.

Ready to used jsfiddle http://jsfiddle.net/ar0zrxwc/


Solution

  • It's not an issue with splice(), it's an issue with your scoping of this.

    Change your removal function to this:

    function wishlist_rem(num) {
    
         var idx = parseInt($(this).attr('value')));
         $(this).parent().slideUp("slow", function () {
             wishlistArray.splice(idx, 1));
             wishlist_show();
    
         });
         $('#myDIV2').append('<br>Remove ' + wishlistArray[parseInt($(this).attr('value'))] + ' of element' + +$(this).attr('value'));
     }