Home > Software design >  try to use local storage in JS but not working
try to use local storage in JS but not working

Time:11-16

HTML code :

<body>
    <input type="text" id="inp" />
    <button type="submit" id="btn">Submit</button>
    <div >Hello</div>
    <script src="app.js"></script>
  </body>

JS Code :

const inputTxt = document.querySelector('#inp');
const btn = document.querySelector('#btn');
const dom = document.querySelector('.dom');

btn.addEventListener('click', () => {
  let txtValue = inputTxt.value;

  localStorage.setItem('inputX', txtValue);
  const storegGet = localStorage.getItem('inputX');

  dom.textContent = storegGet;
});

When I try to call localStorage.getItem into textContent and refresh the browser still not saved I can't figure out the problem.

CodePudding user response:

Finally figure out the problem :)

const inputTxt = document.querySelector('#inp');
const btn = document.querySelector('#btn');
const dom = document.querySelector('.dom');

function callBtn() {
  let txtValue = inputTxt.value;

  localStorage.setItem('inputX', txtValue);
  dom.textContent = txtValue;
  inputTxt.value = '';
}

btn.addEventListener('click', callBtn);

function getStorage() {
  if (btn) {
    dom.textContent = localStorage.getItem('inputX');
  }
}

getStorage();

  • Related