Having an issue with Local Storage returning undefined

I've been working on a form to input values and show the data on a different page after submission. Below is my form:

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/checkout.css">
<p id="Header">Checkout page</p>
<div class="row">
  <div class="col-75">
    <div class="containeer">
      {{!-- When fom submitted, transport to here --}}
      <form id="form" action="receipt" style="checkout.css">
      
        <div class="row">
          <div class="col-50">
            <h3>Billing Address</h3>
            {{!-- Name --}}
            <label for="name"><i class="fa fa-user"></i> Full Name*</label>
            <input class="form-control" type="text" placeholder="Example: Chia Kai Jun" id="name" required />

            <label for="email"><i class="fa fa-envelope"></i> Email*</label>
            <input class="form-control" type="email" id="email" placeholder="Example: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de7e2e5e3cde8f5ece0fde1e8a3eee2e0">[email protected]</a>" required />
            
            <label for="adr"><i class="fa fa-address-card-o"></i> Address (Street, Block, Unit Number)*</label>
            <input class="form-control" type="text" id="adr" name="address" placeholder="Example: Ang Mo Kio Street 69, Blk106P, #07-212" required />

            <div class="row">
              <div class="col-50">
                <label for="zip">Zip*</label>
                <input class="form-control" 
                oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
                {{!-- Javascript code needed here to prevent using text --}}
                pattern="\d*" maxlength="6" type="number" id="zip" name="zip" placeholder="Example: 123456" required />
              </div>
            </div>
          </div>

          <div class="col-50">
            <h3>Payment</h3>
            {{!-- Available credit cards to use with image --}}
            <label for="fname">Accepted Cards</label>
            <div class="icon-container">
              <i class="fa fa-cc-visa" style="color:navy;"></i>
              <i class="fa fa-cc-mastercard" style="color:red;"></i>
            </div>
            
            <label for="cname">Name on Card*</label>
            <input class="form-control" type="text" id="cname" name="cardname" required />
            
            <label for="ccnum">Credit card number*</label>
            <input class="form-control" type="text" maxlength="19" id="ccnum" name="cardnumber" placeholder="Example: 1111-2222-3333-4444"required />
                        
            <div class="row">
              <div class="col-50">
                <label for="expyear">Exp Month and Year*</label>
                <input class="form-control" type="month" id="expyear" name="expyear" required />
              </div>
              <div class="col-50">
                <label for="cvv">CVV*</label>
                <input class="form-control" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
                type="password" id="cvv" name="cvv" pattern="\d*" minlength="3" maxlength="3" required />
              </div>
            </div>
          </div>
          
        </div>
        {{!-- Will link to thank you for purchase, but now link to base for testing --}}
        <button type="submit" class="btn btn-primary" onclick="submitForm()">Submit</button><span id="hi">* - Must be filled in</span>
    </div>
  </div>
  <div class="col-25">
    <div class="container">
      <h4>Cart <span class="price" style="color:black"><i class="fa fa-shopping-cart"></i></span></h4>
      {{!-- Will be currently empty if nothing and have items if something there --}}
      <p id="item">Thinkpad Laptop - $100</p>
      <img class="card-img-top p-5" src="/images/laptop.png" id="laptopimage">
      <hr>
      <p id="price" value="$100">Total: $100 <span class="price" style="color:black"></span></p>
      {{!-- Will display nothing if there are no items and will compute total cost if there are items --}}
    </div>
  </div>
</div>
</form>
<script>
function submitForm(){
  let name = document.forms["form"]["name"].value;
  let email = document.forms["form"]["email"].value;
  let address = document.forms["form"]["address"].value;
  let zip = document.forms["form"]["zip"].value;
  let test = document.forms["form"]["test"].value;
  if (name == "") and (email == "") and (address == "") and (zip == "") and (test == ""){
    return false;
  }
  else if(typeof(localStorage) != "undefined"){
    localStorage.name = document.getElementById("name").value;
    localStorage.email = document.getElementById("email").value;
    localStorage.adr = document.getElementById("adr").value;
    localStorage.zip = document.getElementById("zip").value;
    localStorage.test = document.getElementById("test").value;
  }
  document.getElementById("form").submit();
}
</script>

Here's the code to display the input data:

    .yeet{
        font-size: 25px;
        line-height: 200%;
        padding: 40px;
    }
    .intro{
        text-align: center;
    }
</style>
<div class="intro">
<h1>Thank you for your purchase!</h1>
<h2>Please check that your checkout details are correct</h2>
</div>
<body onload="setData()">
<div class="yeet">
Name: <span id="name"></span><br>
Email: <span id="email"></span><br>
Address: <span id="adr"></span><br>
Zip: <span id="zip"></span><br>
Item: <span id="cvv"></span><br>
</div>
<script>
function setData(){
    if(typeof(localStorage) != "undefined"){
        document.getElementById("name").innerHTML = localStorage.name;
        document.getElementById("email").innerHTML = localStorage.email;
        document.getElementById("adr").innerHTML = localStorage.adr;
        document.getElementById("zip").innerHTML = localStorage.zip;
        document.getElementById("cvv").innerHTML = localStorage.cvv;
    }
}
</script>
</body>

After inputting data, I want to display Name, Email, Address, ZIP, and CVV. However, the CVV is showing as undefined while other values are displaying correctly. Unsure of the issue.

Answer №1

If you want to interact with localStorage by setting or getting data, follow these steps:

localStorage.setItem('variable_name', 'value');
localStorage.getItem('variable_name');

Answer №2

Here is a code snippet that you can try out.

<script>
    function saveData(){
       if(typeof(Storage) !== "undefined"){
            localStorage.name = document.getElementById("name").innerHTML;
            localStorage.email = document.getElementById("email").innerHTML;
            localStorage.adr = document.getElementById("adr").innerHTML;
            localStorage.zip = document.getElementById("zip").innerHTML;
            localStorage.cvv = document.getElementById("cvv").innerHTML;
        }
    }
</script>

We are checking the condition because some browsers do not support Web Storage.

if(typeof(Storage) !== "undefined")

Answer №3

After some investigation, I realized that my issue was actually due to the incorrect placement of my closing </form tag. Apologies for the oversight and a huge thank you to all those who provided assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for a Simplemodal popup to appear only once per user session

I'm completely new to javascript and jQuery. Recently, I've started using SimpleModal basic from SimpleModal to show a popup upon visitors landing on my website. Everything seems to be working perfectly, but there's one issue - the popup kee ...

Bootstrap tab toggle feature

I'm currently facing an issue with Bootstrap's tab component. I need help figuring out how to hide a lorem ipsum section and show a hidden div when a specific tab is clicked, and then revert the changes when a different tab is selected. $(func ...

Is there a way to adapt my existing navigation bar to collapse on smaller devices?

Struggling to make my navigation bar collapsible on my site designed for a class project. Wondering if this requires both HTML and CSS, or can it be achieved with just HTML since this is my first time working on responsive design. Below is the code I have ...

The H1 tag is mysteriously displaying padding or margin on the bottom, despite not being set

Despite not setting any padding or margin for the H1 tag, it still appears to have some spacing at the bottom. After applying a margin and padding of 0 to both the h1 tag and the text below it, I am still facing an issue where the text doesn't align ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

Holding off on executing the event handler until the completion of another function

On our website, we've integrated a 3rd party solution that cannot be directly updated. However, I can insert my own JavaScript code to manipulate the solution. This third-party tool includes a button that triggers an AJAX request. Before this request ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Incorporating the <sub> element while maintaining the line height

I am facing a challenge with formatting text that includes subscripts and superscripts tags. For example: <div>hello <sub>world</sub>, how are you? Translated as logical aggregates or associative compounds, these characters have been int ...

What is the best way to apply CSS max-left or min-left positioning to an absolute element?

I currently have an element with the CSS properties: position:absolute; left: 70%; Is there a way to restrict this element from moving more than 900px from the left side? Similar to max-width but for positioning? ...

Eliminate Redundancy with Knockout.js Copy Prevention

When I combine both ko.js files, one of them ends up being overshadowed by the other. Specifically, the second one stops working while only the first one remains functional. How can I merge these files together to ensure they work properly without any conf ...

The PHP SDK function works flawlessly in the local host environment and in console, however, it fails to perform on the browser when deployed

My PHP function is behaving differently between the server's command line and the web page, with successful execution on a local WAMP host. Any thoughts on what could be causing this inconsistency? function getCFTemplateSummary($CFUrl){ //init client ...

The Datalist feature in HTML5 offers an auto-suggest functionality that displays a list of options beginning with the

In my project, I am utilizing HTML5 Datalist for autosuggestion. By default, HTML5 follows the keyword contains approach rather than the starts with approach. For example, if my datalist includes one, two, three and I type "o" in the search box, it displ ...

Creating a visually appealing chart similar to Excel can be achieved using JavaScript with a whopping 64382 lines of JSON data. No need for Chart.js or any additional tools - simply rely on JavaScript, HTML, and CSS to

I have a project that is due in just a few hours and I need to create a detailed chart using a large set of 64382 lines of JSON data. My knowledge of javascript is limited, so I am struggling to come up with ideas on how to approach this task. While I have ...

Tips for using jQuery to identify the most recently modified row in an HTML table

Is there a way to identify the most recently modified (either newly added or changed) row in an HTML table? ...

Having trouble with sending a list of items from a VueJS form

I have a VueJS application that calls a patch method to update a user's profile. For example, I am attempting to update the field cities. I created a serializer and views.py using Postman during development. I used Postman to call the patch method fo ...

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05. The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues: The calculated value should be rounded to two decimal points. For ex ...

Using CDN to bring in Bootstrap, without triggering animations

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>E ...

Comparing json results from ng-repeat against an array

Currently, I am working with a JSON result that appears in an ng-repeat and I want to filter it based on separate data objects or arrays: Controller.js $scope.jsonResult = [ { "id": "a123" }, { "id": "b456" } ] HTML <span ng-repeat="r in js ...