Burak Burak - 2 months ago 5
Javascript Question

Type a text, push it to array and save in localstorage

In my code, i am typing a word and trying to push it to my array.

When i push an item, it saves but when add another one, last added item changes and only last typed item shows up in array.What is wrong with my code ?

Why i can't push multiple items to array ?

$(function() {

var arr = [];

$(".yourWordButton").click(function() {
var word = $.trim($(".yourWord").val());
word = word.split(' ').join('');
$(".yourWord").val('');

localStorage.setItem('word', word);

return false;
});

if (localStorage.getItem('word')) {
arr.push(localStorage.getItem('word'));
}
console.log(arr);

});


JS BIN

After adding, hit 'Run with Js' button to see what is in array.

Answer

You can try this one:: $(function() {

   var arr = [];

  $(".yourWordButton").click(function() {
    var word = $.trim($(".yourWord").val());
     word = word.split(' ').join('');
    $(".yourWord").val('');
    localStorage.setItem('word', word);
    if (localStorage.getItem('word')) {
            arr.push(localStorage.getItem('word'));
    }
    console.log(arr);
    return false;
  });
});
Comments