0

Hi I need some help to add new objects to local storage every time I when I fill out a form and click on submit, I want to add new item to local storage is it possible? please advice and or help with my code below. thanks for the help. Everytime when I select from a dropdown value.

My dropdown form:

          <form asp-action="Create">
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="ScheduleStartTime" class="control-label"></label>
                <input asp-for="ScheduleStartTime" class="form-control" id="scheduleStartTime" />
                <span asp-validation-for="ScheduleStartTime" class="text-danger"></span>
            </div>
    <select asp-for="CandidateID" class="form-control" id="candId">
                @{
                    if (candidates != null)
                    {
                        foreach (var cand in candidates)
                        {
                            <option value='@cand.ID'>@cand.DisplayName</option>
                        }
                    }
                }
            </select>

  <div class="form-group">

                <input onclick="addTheEvent(); return false;" type="submit" value="Add  " class="btn btn-primary" />

            </div>

        </form> 

here is my code:

     <script>

    var addToTheContent = document.getElementById("canvas");
    var scheduleEvent = document.getElementById("scheduleStartTime");
    var candidateId = document.getElementById('candId');
    var getCandId = document.getElementById("candId");

     var displayCandId = getCandId.options[getCandId.selectedIndex].value;



  function addTheEvent() {



      var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";


      localStorage.setItem("key", showText)  
      localStorage.getItem("key");


  }




</script> 

Updated:

 function addTheEvent() {

    var showText = addToTheContent.innerHTML = displayCandId + " (" + scheduleEvent.value + ") ";

     //set value into local storage

     localStorage.setItem("key", JSON.stringify(showText));
    localStorage.getItem('key');

 // localStorage.getItem("key") // get value from localStorage
  window.location.href = "/"; 
  }
devArm
  • 15
  • 5
  • 1
    local storage stores strings. The question is not really clear on what your problem is. – epascarello Mar 31 '20 at 20:35
  • It is, and "how" is a matter of searching for how to intercept a form submission in javascript, and looking up how to use localStorage's `get` and `set` with objects (hint: you can't store objects, but JSON exists, which means you can store anything you want as long as it's under localStorage's size limit). – Mike 'Pomax' Kamermans Mar 31 '20 at 20:36
  • please see updated question @epascarello .. let me know if it does not make sense still – devArm Mar 31 '20 at 20:37
  • https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – epascarello Mar 31 '20 at 20:38

3 Answers3

1

To save your object in the localStorage try this:

let user = {
    name: "Ivan",
    surname: "Petrov"
}

//save data
localStorage.setItem('user', JSON.stringify(user))

//get data
let user = JSON.parse(localStorage.getItem('user'))
Mark Minerov
  • 309
  • 1
  • 8
  • hey @Mark thanks for your answer however is this okay. – devArm Mar 31 '20 at 20:41
  • `localStorage.setItem("key", JSON.stringify(showText)) let event = JSON.parse(localStorage.getItem('getCandId')) Console.log(event);` – devArm Mar 31 '20 at 20:41
  • `showText` should be only an array or an object to turn it into a JSON string – Mark Minerov Mar 31 '20 at 20:45
  • ok, so with the code I showed you above it just ovewrites the current key value and not add another, why will that even happen? – devArm Mar 31 '20 at 20:48
  • This answer is correct and should work without issue. However, I think it is still worth noting: `localStorage.getItem()` might return `null` and `JSON.parse()` expects a string. – Marc Barbeau Mar 31 '20 at 20:55
  • so, I did not get my answer how the code above can add another value to the `localStorage`? – devArm Mar 31 '20 at 21:03
  • Use different keys: `localStorage.setItem('key1', ...)` `localStorage.setItem('key2', ...)` `localStorage.setItem('key3', ...)` Did you mean that? – Mark Minerov Mar 31 '20 at 21:04
  • Do I need to hardcode keys? i just dont want to hardcode sets like that? .. also, do you know google calendar api (javascript) ? – devArm Mar 31 '20 at 21:06
  • No, i dont know. You should not. You do something like that: `let a = 'YourKey'; localStorage.setItem(a, ...)` Also can you mark my answer as an answer? – Mark Minerov Mar 31 '20 at 21:07
  • So, I did `localStorage.setItem("key", JSON.stringify(showText)); localStorage.setItem("key1", JSON.stringify(showText));` and still does not add a new value - it only overwrites – devArm Mar 31 '20 at 21:09
  • check my new answer – Mark Minerov Mar 31 '20 at 21:13
0
//here i add new value to the storage

const user = {
  name: "Mark",
  surname: "Minerov"
}

localStorage.setItem('key1', JSON.stringify(user))

//then i get the value
const result = localStorage.getItem('key1')

console.log(result)
Mark Minerov
  • 309
  • 1
  • 8
  • please see my updated code above. it did not work. OR if you can apply your code to mine so I can see what I have missed – devArm Mar 31 '20 at 21:17
  • Check up your code it does not even work https://codepen.io/mark-minerov/pen/NWqJagq How can I help you then? – Mark Minerov Mar 31 '20 at 21:28
0

Mark Minerov's answer is correct

I just want to add the answer. If you want to add new value instead of overwriting it every time you click your button, then you should use a dynamic key when you call localStorage.setItem()

    <script>

        var addToTheContent = document.getElementById("canvas");
        var scheduleEvent = document.getElementById("scheduleStartTime");
        var candidateId = document.getElementById('candId');
        var getCandId = document.getElementById("candId");

        var displayCandId = getCandId.options[getCandId.selectedIndex].value;

        var id = 1;

        function addTheEvent() {

          var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";

          localStorage.setItem(`key${id}`, JSON.stringify(showText))
          id += 1  
        }
</script> 
  • So, it does add the keys in the local storage but it wont display on the page? also the keys it always get the first index when I choose from the dropdown – devArm Mar 31 '20 at 22:40
  • which dropdown? your question is about adding a new item in the local storage, and it does. if you want to get the correct item from local storage, you need to call localStorage.getItem with dynamic key. You have to specify which key you want to get, for example, key1, key2, key3, if you don't use a dynamic key, you will end up with getting the first item from local storage. So, In your case, please make sure you use the dynamic key when getting data from local storage. After getting the data, displaying the content is all up to you. – cahyonobagus Apr 01 '20 at 03:41
  • See updated question with the dropdown `select` option @cahyonobagus. – devArm Apr 01 '20 at 13:24
  • I also do `const result = localStorage.getItem("key${id}");` to get the correct item but it always get the first index in the dropdown value – devArm Apr 01 '20 at 13:36
  • and also when I choose from the dropdown it always show the first index because of `.value()` it is good with the dropdown but I do `var displayCandId = getCandId.options[getCandId.selectedIndex].text;` it shows the first index name in the dropdown all the time – devArm Apr 01 '20 at 13:47