Home > Net >  Query / Json How can I save Data and Heading name in my local storage?
Query / Json How can I save Data and Heading name in my local storage?

Time:01-29

  $(document).ready(function () {
                $(":button").click(function () {
                    var btn = $(":button").val();
                    
                    if (btn == 'Favoritisieren')
                    
                   
                  $(":button").css("background-color", "red").prop('value', 'Favoritisiert');
                  
                  
                   var obj = {"Hed.1" : $("h1")}; 
                   var myJSON = JSON.stringify(obj);
                   localStorage.setItem('myJSON'); 
              
                    else
                    $(":button").css("background-color","blue").prop('value','Favoritisieren');
                   
                });
               
         });

hey, I would like to save the filename and H1 value locally when clicking the button. These should also delete themselves later when the button is pressed again. Does anyone maybe have an idea where my error lies?

CodePudding user response:

Assuming we have a button and h1 like this :

<button value="Favoritisieren">click me</button>
<h1>Hello World</h1>

You can do it like this :

$(":button").click(function () {
            var btn = $(this).val();
            if (btn == 'Favoritisieren') {
                $(this).css("background-color", "red").prop('value', 'Favoritisiert');
                localStorage.setItem('Hed.1', $("h1").text());
            } else {
                localStorage.removeItem('Hed.1');
                $(this).css("background-color","blue").prop('value','Favoritisieren');
            }
        });

The syntax to write on localStorage :

localStorage.setItem('myCat', 'Tom');

The syntax for reading the localStorage item is as follows:

const cat = localStorage.getItem('myCat');

The syntax for removing the localStorage item is as follows:

localStorage.removeItem('myCat');

The syntax for removing all the localStorage items is as follows:

localStorage.clear();

CodePudding user response:

Use localStorage.setItem(name, value) to save a named item, var value = localStorage.getItem(name) to read an item, and localStorage.removeItem(name) to delete an item.

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Your code fixed to save the JSON, and to delete it later.

$(document).ready(function () {
  $("button").click(function () {
    var btn = $("button").text();
    if (btn == 'Favoritisieren') {
      $("button").css(({backgroundColor: "red"}).text('Favoritisiert');
      var obj = {"Hed.1" : $("h1").text()}; 
      var myJSON = JSON.stringify(obj);
      localStorage.setItem('myJSON', myJSON); 
    } else {
      $("button").css({backgroundColor: "blue"}).text('Favoritisieren');
      localStorage.removeItem('myJSON'); 
    }
  });
});
  • Related