0

So, to start with I have:

var tempArray = [];
tempArray.push(get);

In this case, the get variable grabs the html of a cloned div.

What I've tried last:

tempArray.push(get);

var myJSONString = JSON.stringify(tempArray);

var parseString = $.parseJSON(myJSONString);

var finalString = myJSONString.replace(/\r?\\n/g, '').replace(/\\/g, '').replace(/^\[(.+)\]$/,'$1').replace (/(^")|("$)/g, '');

var joinString = tempArray.join(",");

And then:

// Save
localStorage.setItem('sessions', finalString);

What I always get:

tempArray[div "," div]

I've declared the array outside the function as:

var tempArray = [];

I'm pushing content to the array here:

  // Decide to add or remove
  if(box.hasClass("selected")){
    console.log("Add to array")
    tempArray.push(get);

    // Add to favorites tab
    favoriteTab.append(boxContent);

  }

Full JS

console.clear();
//localStorage.setItem('sessions', "");

var tempArray = [];

// Clones
$('div.tab-pane').on('click', '.favorite', function(e) {
  e.preventDefault();

  // Elements we play with... Having significative variable names.
  var heartLink = $(this);
  var box = heartLink.parent('.box');
  var container = box.parent('.box-container');
  var favoriteTab = $("#fav .spaces");

  // I don't know what is the use for those 3 lines below.
  var idFind = box.attr("id");
  var idComplete = ('#' + idFind);
  console.log(idComplete);

  //TOGGLE FONT AWESOME ON CLICK
  heartLink.find('i').toggleClass('fa-heart fa-heart-o'); // .selected or not, you need those 2 classes to toggle.
  box.toggleClass("selected not-selected"); // Toggle selected and not-selected classes

  // Clone div
  var boxContent = container.clone(true, true);

  // Change the id
  var thisID = boxContent.attr("id")+"_cloned";
  boxContent.attr("id", thisID);

  // Get the html to be saved in localstorage
  var get = boxContent.wrap('<p>').parent().html();
  get = get.replace(/\r?\n/g, "").replace(/>\s*</g, "><"); // remove line feeds and spaces
  console.log(get);
  boxContent.unwrap();

  // Decide to add or remove
  if(box.hasClass("selected")){
    console.log("Add to array")
    tempArray.push(get);

    // Add to favorites tab
    favoriteTab.append(boxContent);

  }else{
    console.log("Remove from array");
    var index = tempArray.indexOf(get);
    tempArray.splice(index);

    // Remove from favorite tab
    favoriteTab.find("#"+thisID).remove();
  }

  // Save
  localStorage.setItem('sessions', tempArray);

});

// Append item if localstorage is detected
if (localStorage["sessions"]) {
  $("#fav .spaces").append(localStorage["sessions"]);
  console.log( localStorage.getItem('sessions') );
}

Full html

<section id="speakers-programme">
  <div class="container">
    <div class="tabs_main">

      <div class="col-md-5"><a data-target="#mon" class="btn active" data-toggle="tab">Monday</a></div>
      <div class="col-md-5"><a data-target="#tue" class="btn active" data-toggle="tab">Tuesday</a></div>
      <div class="col-md-2"><a data-target="#fav" class="btn active" data-toggle="tab"><i class="fa fa-heart" aria-hidden="true"></i></a></div>

    </div>

    <div class="tab-content">
      <div class="tab-pane active" id="mon">
        <br>
        <div class="spaces">
          <div class="box-container">
            <div class="box not-selected" id="box1">
              <span>1</span>
              <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
            </div>
          </div>
          <div class="box-container">
            <div class="box not-selected" id="box2">
              <span>2</span>
              <a href="#" class="favorite"><i class="fa fa-heart-o" aria-hidden="true"></i></a>
            </div>
          </div>
        </div>
      </div>

      <div class="tab-pane active" id="tue">
        <br>
        <div class="spaces">
        </div>
      </div>

      <div class="tab-pane active" id="fav">
        <br>
        <div class="spaces">
        </div>
      </div>

    </div>
  </div>
</section>

Fiddle: https://codepen.io/Bes7weB/pen/NvQQMN?editors=0011

So, in this example if you click on the tab "Monday" and click on both hearts, the parent div will be cloned to the "favorites" tab and then if you refresh the page you'll see both divs with a comma at the middle.

Any help is appreciated, many thanks!

  • `join` does indeed not *affect* the array. It returns a new string. – Bergi Sep 11 '17 at 12:17
  • Please post the particular code that has a problem in your question, not just a link to it. Where and how are you using `tempArray` so that it gets that unwanted comma? – Bergi Sep 11 '17 at 12:18
  • I've updated the question @Bergi – catarina melim Sep 11 '17 at 12:30
  • Ah, you're using `localStorage`. The problem is that it does not store objects, it does store strings - and your array is implicitly getting stringified with the standard method that yields a comma separator. You will want to explicitly use `JSON.stringify` and `JSON.parse` instead. – Bergi Sep 11 '17 at 12:35
  • Ok, I understand. I've tried that way but still have a comma at the end to delete and don't know how to do it.. can you please show me a way of doing this? Thank you. @Bergi – catarina melim Sep 11 '17 at 13:07
  • Please [edit] your post to show how you tried it – Bergi Sep 11 '17 at 13:57
  • I've updated the question. I'm in a very tight deadline, so if you could help asap that would be great @Bergi – catarina melim Sep 11 '17 at 18:47
  • What did you intent to do with `parseString`, `finalString`, `joinString`?! Just save the `myJSONString` and be done with it. Then, when *accessing* the memory, you need to do `JSON.parse(localStorage.getItem(…))`. – Bergi Sep 12 '17 at 06:42

1 Answers1

0

you need to update the array, take a look at the below example

let arr = [1, 2];
arr.join(' ');

console.log(arr);

arr = arr.join(' ');

console.log(arr);
marvel308
  • 9,972
  • 1
  • 18
  • 31
  • Thank you for your response. It makes sense. However after changing my code to tempArray = tempArray.join(' '); it gives me an error which says: tempArray.push is not a function. Do you have any idea why I'm getting this error? – catarina melim Sep 11 '17 at 10:16
  • https://stackoverflow.com/questions/1424710/why-is-my-join-on-a-javascript-array-failing – marvel308 Sep 11 '17 at 10:23
  • I've ticked your answer as right because it made me see how things work in this case.. but in fact, I couldn't make it work yet. Can you take a look? https://codepen.io/Bes7weB/pen/NvQQMN?editors=0011 So, if you click in the tab "Monday" and click on both hearts, the parent divs will be cloned to the "favorites" tab and then if you refresh the page you'll see both divs with a comma at the middle. Please help :) @marvel308 – catarina melim Sep 11 '17 at 11:29
  • I would take a look in a while, you could try asking in https://codereview.stackexchange.com/ , you can find great help their – marvel308 Sep 11 '17 at 11:33