Home > Blockchain >  JavaScript/Local Storage
JavaScript/Local Storage

Time:03-06

Good Afternoon, I'm hoping for some guidance. I am new to JavaScript and struggling with a project. We have been asked to store new entries into a website application, which once added store into the local storage.

This is what I have so far, but I am at a loss where I am going wrong to get this stored.

The first section surrounded by ** works fine (albeit it doesn't store the entires). It is the last bit where I'm trying to add new code to store the message and invoke the event listener which doesn't work.

Any guidance would be greatly appreciated.

    **function addTextEntry(itemKey, initialText, isNewEntry) {
    // Create a text element to edit the entry
    var textElement = document.createElement("textarea");
    textElement.rows = 5;
    textElement.placeholder = "(new entry)";
    // Set the textarea's value to the given text (if any)
    textElement.value = initialText;
    // Add a section to the page containing the textarea
    addSection(itemKey, textElement);
    // If this is a new entry (added by the user clicking a button)
    // move the focus to the textarea to encourage typing
    if (isNewEntry) {
        textElement.focus();
    }**

    // Create an event listener to save the entry when it changes
    
    function saveEntry() {
        // A new version of this function is created every time addTextEntry is called,
        // so it can access all the variables available in this call to addTextEntry
        console.log("saveEntry called with variables in scope:", {
            itemKey,
            initialText,
            isNewEntry,
            textElement,
        });
        
        document.getElementById(initialText);
        item = makeTextItem(initialText); 
        localStorage.setItem(itemKey);  
        textElement.addEventListener("initialText", saveEntry); 
        
    }
    
    }

CodePudding user response:

setItem method takes 2 parameters:

  • keyName: The name of the key in the Local Storage
  • keyValue: The value for a given key

In you code, you are passing only one parameter itemKey. You should also pass the value for that key as a second parameter.

CodePudding user response:

document.getElementById(initialText);

This statement doesn't do anything with the result. You may want to assign it to a value like const textElement = document.getElementById(initialText);

item = makeTextItem(initialText);

You are missing the code for makeTextItem but that's still irrelevant since item isn't being used anywhere in the code below it.

localStorage.setItem(itemKey);

setItem takes TWO params, the key and the thing you want to save storage.setItem(keyName, keyValue);

textElement.addEventListener("initialText", saveEntry);

addEventListener's first argument should be a valid event. addEventListener(type, listener);

  • Related