简体   繁体   中英

How can i add elements to an array and then add the arrays new value to localStorage?

I am trying to create an admin panel where you add the words inside the input and then you add these words to an array which updates his value and adds it to the localStorage.

I've tried to add an event listener to a button but when i click it the first time it adds the value but when i click it second time it's adding the same value.

let input = document.querySelector('.word-input');
let inputValue = input.value;
let btn = document.querySelector('.btn');
let p1 = document.querySelector('#p2');
let form = document.querySelector('form')[0];


form.addEventListener('submit', function() {
    arr.push(inputValue);

})

localStorage.setItem('a', arr);

I expect the values inserted to the input get inserted to the localStorage also but it adds the same value every time.

It keeps inserting the same value because you created let inputValue = input.value; but you should take the input value everytime the event gets triggered.

In addition, you should put your localStorage.setItem into the event since you want to add the value to your array and then save the array into the localStorage.

Finally, you should stringify your array to save it as a string into your localStorage since you cannot save arrays into localStorage.

form.addEventListener('submit', function() {
    arr.push(input.value);
    localStorage.setItem('a', JSON.stringify(arr));
})

Your inputValue variable is only set on initial load.

form.addEventListener('submit', function() {
    let inputValue = input.value;
    arr.push(inputValue);
})```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM