Home > Back-end >  Using javascript to save a text entry to local storage
Using javascript to save a text entry to local storage

Time:03-06

I am trying to use javascript to save a text entry using local storage with little success could anyone offer any advice please as i'm new to javascript. It is for a basic blog post site where the user submits text into a diary entry. I'm particularly unsure about how to get the textarea elements current value as shown in the code below and think that is where im going wrong.

function addTextEntry(itemKey, initialText, isNewEntry) {
  // Create a textarea element to edit the entry
  var textElement = document.createElement("textarea");
  textElement.rows = 5;
  textElement.placeholder = "(new entry)";

  textElement.value = initialText;

  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() {
    console.log("saveEntry called with variables in scope:", {
      itemKey,
      initialText,
      isNewEntry,
      textElement,
    });


    // Save text entry
    // ...get the textarea element's current value
    textElement = document.getElementById;
    // ...make a text item using the value
    textElement.value = initialText;
    //    (demonstrated elsewhere in this file)
    // ...store the item in local storage using the given key
    localStorage.setItem(itemKey);
  }

  // Connect the saveEntry evenFt listener to the textarea element 'change' event
  textElement.addEventListener("change", saveEntry);
  // (demonstrated elsewhere in this file)
}

CodePudding user response:

Looks like you're using getElementById wrong.

Try the following to get the current value of a <textarea>:

function logTextareaValue () {
  const element = document.getElementById('myTextarea')
  const value = element.value
  console.log(value)
}
<textarea id="myTextarea">Default text</textarea>
<button onClick="logTextareaValue()">Click to log textarea value to console</button>

CodePudding user response:

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

localStorage.setItem(itemKey, itemValue);
  • Related