Home > Net >  How can I save a value to localStorage in a dynamically generated jquery list, while also generating
How can I save a value to localStorage in a dynamically generated jquery list, while also generating

Time:04-16

I am pulling a list of file names from my database and listing them dynamically with jquery. They are added to the html as an unordered list. I want each item to link to my details page, but also I need the file id to save to local storage on click. Is this possible? Do I just need work on my syntax? Any help is appreciated.

jquery function:

$(function() {
  var $files = $('#files');
  $.ajax({
      type: "GET",
      url: 'some url',
      data: {},
      success: function(files) {
        $.each(files, function(i, file){
          $files.append('<a href="details.html" onclick="localStorage.setItem("file",  file.id )";>' file.id '</a>');
        });
      },
      // Error handling 
      error: function (error) {
      console.log(`Error ${error}`);
      }
  });
})

HTML

<ul id="files"></ul>

CodePudding user response:

You've got double quotes inside of double quotes, and some random "plus" signs.

Change your code to this, to use a template literal instead: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)

$files.append(`<a href="details.html" onclick="localStorage.setItem('file', '${file.id}')";>${file.id}</a>`);

Using string templates will allow you to directly print the value of a variable into the string with ${variableName}


Oops, I misunderstood the question, leaving this answer on how to cache a list in localStorage in case someone needs it:

Before you pull from your database, see if it exists in local storage:


$(function() {
    let storedFiles = window.localStorage.getItem('stored_files');
    
    if(storedFiles !== null) {
        //found in local storage, use this:
        files = JSON.parse(storedFiles); //local storage is stored as a string, you have to convert back to an object
    
        //generate the list of files
        generateListOfFiles(files);
    } else { 
        // not found in local storage, get from database
        
        $.ajax({
          type: "GET",
          url: 'some url',
          data: {},
          success: function(files) {
            //generate the list of files:
            generateListOfFiles(files);
    
           // now store the files back in local storage for next time!
           window.localStorage.setItem("stored_files", JSON.stringify(files)); // local storage should be stored as a string, as mentioned above
          },
          // Error handling 
          error: function (error) {
          console.log(`Error ${error}`);
          }
        });
        
        
    }

    function generateListOfFiles(files) {
        $.each(files, function(i, file){
            let $files = $('#files');
    
            $files.append('<a href="details.html" onclick="localStorage.setItem("file",  file.id )";>' file.id '</a>');
        });
    }
});
  • Related