Search code examples
javascriptjquery-tokeninput

Restoring values to tokeninput field - jquery error


I'm trying to take values from a tokeninput field, save them to localstorage then retrieve them later. I am getting an error. Code:

//Save to storage
 var selectedValues = $('#Contacts').tokenInput("get");
console.log(JSON.stringify(selectedValues));
localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));

//Restore
var names = localStorage.getItem("ContactsJSON");
console.log(names);
$.each(names, function (index, value) {
    $("#Contacts").tokenInput("add", value);
});

Error message is:

Invalid operand to 'in': Object expected

Error is showing at jquery-1.10.2.js (1009,2)

I'm quite sure that my JSON is correct, as per the tokeninput docs, it should be in the right format when retrieved using the get API:

selector.tokenInput("get"); Gets the array of selected tokens from the tokeninput (each item being an object of the kind {id: x, name: y}).

The data I can see in localstorage is as follows:

[{id":59,"name":"Steve Carrell"},{"id":58,"name":"John Krasinski"},{"id":1,"name":"Jenna Fischer"}]


Solution

  • I believe that your problem is that you are getting string, not an object.

    You should call JSON.pase() on your string from localstorage.

    So, fixed code should look like:

    // here you are converting object to string:
    localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));
    
    var names = localStorage.getItem("ContactsJSON");
    // here you should convert string back to object
    var names_object = JSON.parse(names);
    console.log(names_object);
    $.each(names_object, function (index, value) {
        $("#Contacts").tokenInput("add", value);
    });