Reputation: 19
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.
Upvotes: 0
Views: 72
Reputation: 402
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));
})
Upvotes: 3
Reputation: 513
Your inputValue
variable is only set on initial load.
form.addEventListener('submit', function() {
let inputValue = input.value;
arr.push(inputValue);
})```
Upvotes: 0