Sadriendel
Sadriendel

Reputation: 17

How can I save user input (adding and deleting) in local storage?

This is a simple to do list. User can delete or add categories. But I have been having trouble figuring out how to save what the user did when refreshing the page. For example I input Homework and delete Vaje, the li element will stay even when refreshing, not reseting the whole thing.

HTML


        <input type="text" id = "dodaj" name="additem">
        <button id="add" onclick="newElement()">Dodaj</button>
        <button id="remove" class="remove" >Zbriši</button>
        <ul id="kategorija" class="notes" >
            <li class="class">Vaje</li>
            <li class="class">Treningi</li>
            <li class="class">Projekt</li>
        </ul>
    </div>







JS

$(document).on('click', '.class', function(){ 
  $('.class')
    .css({ "font-weight": 'normal', "text-decoration": 'none'})
    .removeClass("selectedItem");

  $(this)
    .css({"font-weight": 'bold', "text-decoration": 'underline'})
    .addClass("selectedItem");
});

$(function(){
  $("#add").click(function(){
    var addItem = $("#dodaj").val();
    if(addItem.length > 0) {  
      $("ul").append($('<li class="class"></li>)').text(addItem));
      $("#dodaj").val("");
    }
  });

  $("#remove").click(function() {
    $(".selectedItem").remove();
  });
});





}

Upvotes: 0

Views: 358

Answers (2)

Devin Villarreal
Devin Villarreal

Reputation: 68

First, we need to update our HTML to be ready for initializing on the page load with data stored in the browser's HTML5 Web Storage (https://www.w3schools.com/html/html5_webstorage.asp):

<div>
    <input type="text" id = "dodaj" name="additem">
    <button id="add" onclick="newElement()">Dodaj</button>
    <button id="remove" class="remove" >Zbriši</button>
    <ul id="kategorija" class="notes" >
        <!-- injected via javascript -->
    </ul>
</div>

Next, we need to update our script to handle initializing existing Web Storage data - check for existing and update HTML list display:

// a unique key for this specific area of your application where data will be stored
var unique_key_name = 'user_selection';

// the data from user's previous session fetched on browser init (array of values)
var current_data = window.localStorage.getItem(unique_key_name);
if (!current_data) {
    // set current_data to empty array if none exists (first time initialization, etc)
    current_data = [];
}

// inject array of values into HTML
for (var i = 0; i < existing_data.length; i++) {
    $('ul').append($('<li class="class">' + existing_data[i] + '</li>)'));
}

Next, we want to update our add / remove handling to maintain the state of our current_data array, as well as update the Web Storage with the state of the array:

$('#add').click(function(){
    var addItemVal = $('#dodaj').val();
    if (addItemVal.length > 0) {
        $('ul').append($('<li class="class"></li>)').text(addItemVal));
        $('#dodaj').val('');

        // add item to current_data
        current_data.push(addItem);

        // update browser local storage with the state of current_data
        window.localStorage.setItem(unique_key_name, current_data);
    }
});

$('#remove').click(function() {
    var removeItemText = $('.selectedItem').text();
    $('.selectedItem').remove();

    // remove item from current_data
    current_data = $.grep(current_data, function(value) {
        return value != removeItemText;
    });

    // update browser local storage with the state of current_data
    window.localStorage.setItem(unique_key_name, current_data);
});

I've simplified / fixed the logic in this area to do what it looks like you are trying to achieve - toggle list item selection on / off when clicking on a row:

$(document).on('click', '.class', function() {
    if ($(this).hasClass('selectedItem') {
        $(this)
        .css({ 'font-weight': 'normal', 'text-decoration': 'none'})
        .removeClass('selectedItem');
    } else {
        $(this)
        .css({'font-weight': 'bold', 'text-decoration': 'underline'})
        .addClass('selectedItem');
    }
});

Upvotes: 1

Nicolas
Nicolas

Reputation: 8670

To add / remove items from the localstorage, you need to use the getItem('key') and setItem('key', 'values'). If you want to delete something, you need to use the removeItem('key') function.

let value = 'some cool value';
window.localStorage.setItem('key', value);

console.log(window.localStorage.getItem('key')); // some cool value
window.localStorage.removeItem('key');

console.log(window.localStorage.getItem('key')); // null

Upvotes: 0

Related Questions