yuyu
yuyu

Reputation: 144

How to append data to localStorage item through onclick event?

I have a feature in my app wherein a user selects keywords and these keywords are displayed on a textfield once they are selected. If the page reloads, I want the keywords to remain and at the same time when the user selects more keywords, it will just be displayed along with the initial keywords.

I have checked out and tried this answer Append data to localStorage object but I get "keylocal.push is not a function" error.

if(localStorage.getItem('keywords') == null){

    $('.words').on('click', function(e){
        e.preventDefault();    
        keywords.push( $(this).data('word-name') );
        document.getElementById('display').value = keywords
        localStorage.setItem('keywords', keywords)
        return keywords
        console.log(keywords)
    });
    }

else{
        var keylocal = localStorage.getItem('keywords')
    document.getElementById('display').value = keylocal
    $('.words').on('click', function(e){
        keylocal.push( $(this).data('word-name') );
        localStorage.setItem('keywords', keylocal)
        var keyresult = localStorage.getItem('keywords')
        console.log(keyresult)
        document.getElementById('display').value = localStorage.getItem('keyresult')
        return keywords
    });

}

I expect to be able to display the previous keywords selected and the new keywords through onclick. However, it either only displays the new keywords or I get the .push is not a function error

Upvotes: 0

Views: 1176

Answers (2)

Sunil Kashyap
Sunil Kashyap

Reputation: 2984

try setting items on local storage using JSON.stringify and JSON.parse before pushing.

JSON.parse and JSON.stringify because Local storage only allows you to store string only.

sample working code

if(localStorage.getItem('keywords') == null){

    $('.words').on('click', function(e){
        e.preventDefault();    
        keywords.push( $(this).data('word-name') );
        document.getElementById('display').value = keywords

        localStorage.setItem('keywords', JSON.stringify(keywords)) // <- here

        return keywords
        console.log(keywords)
    });
    }

else{
        var keylocal = JSON.parse(localStorage.getItem('keywords')) // <- here

    document.getElementById('display').value = keylocal
    $('.words').on('click', function(e){
        keylocal.push( $(this).data('word-name') );
        localStorage.setItem('keywords', JSON.stringify(keylocal)) // <- here
        var keyresult = JSON.parse(localStorage.getItem('keywords')) // <- here
        console.log(keyresult)
        document.getElementById('display').value = JSON.parse(localStorage.getItem('keyresult'))
        return keywords
    });

}

Upvotes: 1

Dharmesh Fumakiya
Dharmesh Fumakiya

Reputation: 2338

First you need to get data from localStorage while onClick and append localStorage data with your data.

Upvotes: 0

Related Questions