mOna
mOna

Reputation: 2459

cannot re-add item to basket (array) after it is removed

I have a basket (an array) in my PHP form, where users can add their selected movies to it. The image below, may show the situation better:

enter image description here

Problem: As can be seen in the image, user can click on the garbage image to remove a movie from the list. Now, the problem is that if he/she would like to re-add this removed film to the selected list again, the message is shown "This movie is already in the list"., while it should be shown ONLY IF the movie is not in the list NOW!

This is my code (form.php):

<script type="text/javascript">
var master_basket = new Array();
var selectedMovies = {};

$(document).ready(function () {
/// SOME CODES UNRELATED TO MY QUESTION ....

 function get_index_of_item(movie_name) {
for (var i = 0; i < master_basket.length; i++) {
    if (master_basket[i].movie_name === movie_name){
        return i;
    }
 }
 return -1;
}

function addToBasket(item) {
   master_basket.push(item);
   showBasketObjects();
}

function showBasketObjects() {
   $("#basket_content").empty();
   $.each(master_basket, function(k,v) {
         var name_and_year = v.movie_name;
         console.log(v.movie_name);
         console.log(v.movie_year);          

         $("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
   });

   $(".remove_link").on('click', function (e) {       
     var name_year = $(this).attr("href");
     console.log(name_year);

     var index = get_index_of_item(name_year[0]);
     console.log(index);

    if (index !== -1) {
     master_basket.splice(index, 1);
     console.log(master_basket);
     $(this).closest('.item_list').remove();
    } else {
           console.log("DEBUG: NO ITEM IN THE LIST");
    }
     return false;
  });
}

and this is my UPDATED searchfilm.php:

<?php
// QUERY DB
 while ($row = $query->fetch(PDO::FETCH_ASSOC)):
      ?> 
     <tr>
         <td><img class='imdbImage' id="image" src='imdbImage.php?url=<?php echo $row['posterLink']; ?>' alt="" /></td>

         <td><label id='year'><?php echo $row['year']; ?> </label></td>

         <td><a href="http://www.imdb.com/title/<?php echo urlencode($row['ImdbId']); ?>"><?php echo $row['movieName']; ?></a></td>

        <td><a href="javascript:addmovie('<?php echo $row['movieName'], "_", $row['year']; ?>')" class="add">Add to list</a></td>
     </tr> 
      <?php
       endwhile;
      ?>

<script type="text/javascript">
function addmovie(movieName) {       

    var obj = {
              "movie_name":movieName
              };

    var index = parent.window.opener.get_index_of_item(movieName);

         if(index === -1) {
                parent.window.opener.addToBasket(obj);  
         }  else {
                alert("This movie is already in the selected list");
         }
    }
 </script>

Could someone kindly help me know how to fix it?

Upvotes: 2

Views: 191

Answers (1)

six fingered man
six fingered man

Reputation: 2500

Your .indexOf() search is looking for a string of "The Matrix_1999", but the basket doesn't hold strings. It holds objects with all the movie info. So your .indexOf() was returning -1.

You need a function that will search for the right object in the basket based on the name and year that you give it.

Also, there's no need to add the name/year as properties to the basket.

var master_basket = new Array();

/*** This will receive the movie name/year, 
     and return the index or -1 if not found ***/
function get_index_of_item(movie_name, movie_year) {
    for (var i = 0; i < master_basket.length; i++) {
        if (master_basket[i].movie_name == movie_name &&
            master_basket[i].movie_year == movie_year {
            return i;
        }
    }
    return -1;
}

function addToBasket(item) {
   master_basket.push(item);
   showBasketObjects();
}

// We need to pass along the movie name and year so it can be used to
//  fetch the right index from the array.
function showBasketObjects() {
   $("#basket_content").empty();
   $.each(master_basket, function(k, v) {
         var name_and_year = v.movie_name + "_" + v.movie_year;

         $("#basket_content").append("<div class='item_list'>" + 
                                      v.movie_name + 
                                      "<a class='remove_link' href='" + 
                                      name_and_year + 
                                      "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
   });

 $(".remove_link").on('click', function (e) {
     // Split the `href` on the `_` character to get the name and year
     var name_year = $(this).attr("href").split("_");

     // The split gave us an Array. The name is at the first index,
     //  and the year is at the second
     var index = get_index_of_item(name_year[0], name_year[1]);

     // We check to see if it returned `-1`, and if not, we remove it
     if (index !== -1) {
         master_basket.splice(index, 1);
         console.log(master_basket);
         $(this).closest('.item_list').remove();
     } else {
         console.log("DEBUG: For some reason it was not in the list");
     }
     return false;
  });
}

// I think the `movieName` is getting `"The Matrix_1999"`, so split it on `"_"`
function addmovie(movieName) {
    var name_and_year = movieName.split("_");

    var obj = {
          "movie_name":name_and_year[0],
          "movie_year":name_and_year[1]
    };

    // Use the function to see if the item is already in the list
    var index = parent.window.opener.get_index_of_item(movieName, year);

    // If it returned `-1`, we can add it.
    if(index === -1) {
         parent.window.opener.addToBasket(obj); 
    } else {
         alert("This movie is already in the selected list");
    }
}

Upvotes: 2

Related Questions