-1

I've made a wishlist which works like it should do by adding the product to the wishlist when I press the heart button. However, I have a minor issue! When I add a product to the wishlist and then click on the heart button again, it adds the same product multiple times which is something I do not want. Can anyone help me find some code that only adds the product once so that if that product is already in the wishlist, it won't add it again. Your help would be greatly appreciated! Thanks.

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}


$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "<tr class='wishlist-item' id='list_id_" + $office_id + "'><td class='w-pname'>" + $office_name + "</td><td class='w-premove' wpid='" + $office_id + "'>x</td></tr>";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {


      $("#wish_list_item").append($office_str);

      wish_list.push($office_str);
      //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
      show_message($office_name + " Office Added");
    }
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
  // Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation 
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}
button a {
  color: #fff !important;
}

button {
  font-family: 'open sans', sans-serif;
  font-size: 15px;
}

button {
  text-align: center;
  padding: 1px 7px;
  margin: 0 5px 0;
  border: 4px solid #000;
  background-color: #000;
  vertical-align: middle;
  cursor: pointer;
  white-space: nowrap;
  font-size: 35px;
  color: #fff;
}

#wish_list {
  position: fixed;
  bottom: 0px;
  right: 0px;
  height: 35px;
  width: 400px;
  background: #fff;
  border: 3px solid #22a7c5;
  z-index: 3;
}

#wish_list .wish_list_heading {
  margin: 0px 0px;
  text-align: center;
  color: #fff;
  height: 27px;
  background-color: #22a7c5;
  padding: 6px 3px;
  font-weight: bold;
  cursor: pointer;
  font-size: 18px;
}

#wish_list_item {
  width: 100%;
  text-align: center;
  border-spacing: 0px 4px;
  border-collapse: separate;
}

#msg {
  position: fixed;
  display: none;
  padding: 10px 25px;
  background: #22a7c5;
  border: 1px solid #22a7c5;
  font-size: 18px;
  width: 50%;
  text-align: center;
  font-weight: 700;
  color: #fff;
  z-index: 4;
}

.wishlist-item {
  padding: 10px 5px;
  background: #f1f1f1;
  color: #323470;
}

.w-premove {
  font-size: 20px;
  cursor: pointer;
  width: 7%;
  padding-bottom: 4px;
}

.w-pname {
  font-size: 16px;
  width: 93%;
  text-align: left;
  padding-left: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id='msg'></div>
<div id='wish_list' class='col-s'>
  <p class="wish_list_heading">
    <i class="fa fa-heart-o"></i>
    <span id='p_label'>Shortlist (</span>
    <span id='listitem'>0</span>
    <span id='p_label'>)</span>
  </p>
  <table id='wish_list_item' border='0'></table>
</div>

<div class="btn-group">
  <button class='wishlist' title="Add To Shortlist" office_name='Hampton Street' office_id='hamptonstreet'>
        <span><i class="fa fa-heart">❤️</i></span>
      </button>
</div>
Pather73
  • 9
  • 4
  • You can either put an if condition around the line i.e. adding the item in wishlist so if array already has it, you dont add it (`.include()` can be used to check if an item is already there in the array) or you can use `filter` method as explained in this [SO](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) post – Usman Waheed Feb 10 '22 at 09:11
  • @UsmanWaheed Could you show me an example please? Thanks. – Pather73 Feb 10 '22 at 10:00
  • before this line: `wish_list.push($office_str);` put: `if(!wish_list.includes($office_str)` – Usman Waheed Feb 10 '22 at 15:08
  • @UsmanWaheed Doesn't seem to work....shouldn't there be a rule like don't add or something after the code you suggested? I could be writing it wrong though. if so, can give an example of the full js code please? Thanks. – Pather73 Feb 10 '22 at 15:45
  • I posted it as answer and I did checked it, its working fine – Usman Waheed Feb 10 '22 at 16:02
  • @UsmanWaheed Can you show the whole code please with your added code? I just can't get it to work. Thanks – Pather73 Feb 10 '22 at 16:12
  • basically I just used your code, just added 1 if condition and two curly brackets, I dont know why you cannot get it, still I updated my answer with full code – Usman Waheed Feb 10 '22 at 16:31
  • @UsmanWaheed I've just tested it with the full code and its perfect! Thank you so much! I was trying to do a toggle on the heart to add and remove but nobody seemed to be able to do it so I settled for this way as it seemed easier. You don't happen to know how to do a toggle heart to add and remove do you? it will be fa fa heart-o to add and fa fa heart to remove. – Pather73 Feb 10 '22 at 22:12
  • I updated the code again, toggle is working now. But only glitch is it is not updating the list, please figure it out yourself as I was unable to figure it out. – Usman Waheed Feb 11 '22 at 15:52

1 Answers1

0

I have modified your code a little here is what you need to update: (it checks for include method which returns in true or false based on wether the item is already in the array or not, if its not, it will add item, otherwise)

var wishlistkey = "wishlist";
// try and fetch an existing wishlist from the localStorage.
var wish_list = []; // localStorage.getItem(wishlistkey)

if ($.isEmptyObject(wish_list)) { //nothing was saved previously
  wish_list = new Array()
} else {
  wish_list = JSON.parse(wish_list);
  count_items_in_wishlist_update();
  $('#wish_list_item').html(wish_list);
}


$(document).ready(function() {
  $(".wishlist").on("click", function() {
    $data = "";
    $office_id = $(this).attr("office_id");
    $office_name = $(this).attr("office_name");
    $office_str = "<tr class='wishlist-item' id='list_id_" + $office_id + "'><td class='w-pname'>" + $office_name + "</td><td class='w-premove' wpid='" + $office_id + "'>x</td></tr>";
    //check if the element is in the array
    if ($.inArray($office_id, wish_list) == -1) {



  if(!wish_list.includes($office_str))
  {  
        $("#wish_list_item").append($office_str);
        wish_list.push($office_str);
        //  localStorage.setItem(wishlistkey, JSON.stringify(wish_list))
       show_message($office_name + " Office Added");   
  }
  else
  {
       var myIndex = wish_list.indexOf($office_str);
       if (myIndex!==-1)
       wish_list.splice(myIndex, 1);
       $("#wish_list_item").remove();
       show_message("Office removed");
       count_items_in_wishlist_update();
  }

}
    count_items_in_wishlist_update();
  });

  //adding toggle functionality to the wishlist pannel
  $(".wish_list_heading").on("click", function() {
    if (!$(this).hasClass("up")) {
      $("#wish_list").css("height", "390px");
      $(this).addClass("up");
      $("#wish_list").css("overflow", "auto");
    } else {
      $("#wish_list").css("height", "35px");
      $(this).removeClass("up");
      $("#wish_list").css("overflow", "hidden");
    }

  });
// Remove function
  $("#wish_list_item").on("click", ".w-premove", function() {
    $office_id = $(this).attr("wpid");
    $("#list_id_" + $office_id).remove();
    wish_list = [];

    $("tr.wishlist-item").each(function(index, el) {
      wish_list.push(el.outerHTML);
    });
    //localStorage.setItem(wishlistkey, JSON.stringify(wish_list));

    show_message("Office removed");
    count_items_in_wishlist_update();

  });
});
//Animation 
function show_message($msg) {
  $("#msg").html($msg);
  $top = Math.max(0, (($(window).height() - $("#msg").outerHeight()) / 2) + $(window).scrollTop()) + "px";
  $left = Math.max(0, (($(window).width() - $("#msg").outerWidth()) / 2) + $(window).scrollLeft()) + "px";
  $("#msg").css("left", $left);
  $("#msg").animate({
    opacity: 0.6,
    top: $top
  }, 400, function() {
    $(this).css({
      'opacity': 1
    });
  }).show();
  setTimeout(function() {
    $("#msg").animate({
      opacity: 0.6,
      top: "0px"
    }, 400, function() {
      $(this).hide();
    });
  }, 2000);
}

//Validation against the amount of product being added
function count_items_in_wishlist_update() {
  $("#listitem").html(wish_list.length);
  if (wish_list.length > 1) {
    $("#p_label").html("Shortlist (");
  } else {
    $("#p_label").html("Shortlist (");
  }
}
Usman Waheed
  • 86
  • 1
  • 8