Send the selected items to the next page using a JavaScript onclick function

I have created a 3-step restaurant menu items order form in HTML with JavaScript, but I am facing some issues with the functionality. The main problem lies in the order calculation.

Details of the 3 step form:

  1. In menu.html :

    The user can add menu items by clicking a button (image). The selected items will be displayed on the right side of the same page. Users can then click the checkout button.

  2. In payment.html :

    Here, only the selected items for the order are shown. Users can review them and then proceed to checkout.

  3. In delivery.html :

    Users will see their total order price and need to provide their name, address, city, etc., similar to a registration form. At the bottom, there is a "Place Order Now" button that, when clicked, notifies the site owner.

****** HTML code for menu.html ******

<li>
    <div class="row">
        <div class="col-xs-8">
            <p>Grilled Fish Fillet</p>

        </div>
        <div class="col-xs-2">
            <p>150 SR</p>
        </div>
        <div class="col-xs-2">
            <button onclick="addtoCard('grilledfishfillet','Grilled Fish Fillet', 150)" style="border:none; background:none;"><img src="images/plus.jpg" alt=""></button>

        </div>
</li>

****** Content for delivery.html******

<div id="OrderItem">
    <input name="order1" placeholder="" type="text" id="order1" size="30" value=""  class="form-control  input-lg"><br>
    <input name="order2"  placeholder=" " type="text" id="order2" size="30" value=""  class="form-control  input-lg"><br>
    <input name="order3" placeholder=" " type="text" id="order3" size="30" value=""  class="form-control  input-lg"><br>
    <input name="order4" placeholder="" type="text" id="order4" size="30" value=""  class="form-control  input-lg"><br>
</div>
    

***** Details for payment.html page****

<div class="row">
    <div class="col-sm-6">
    <label>First Name</label>
    <input name="name" type="text" id="name" size="30" value=""  class="form-control  input-lg">
    </div>
    <div class="col-sm-6">
    <label>Last Name</label>
    <input name="lname" type="text" id="lname" size="30" value=""  class="form-control input-lg">
    </div>
</div>

<div style="margin-top:40px;padding:5px 30px;" class="bg-color">
    <div class="row">
        <div class="col-xs-12">
            <h3 style="padding-top:10px; text-align:center; font-size:24px;">Total : 246.00 SAR</h3>
        </div>
        
    </div>
</div>

Answer №1

One method for transferring data between pages is using localStorage. Here's a basic example of how to use it:

if (typeof(Storage) !== "undefined") {
    // Code for localStorage/sessionStorage.
} else {
    // Unfortunately, Web Storage is not supported..
}

To set a value:

localStorage.setItem('myValue', 'My Value');

And to retrieve a value:

localStorage.getItem('myValue');

If localStorage isn't available, you can consider using cookies or URL rewriting as alternatives.

Answer №2

Sending Data Between Two Web Pages using localStorage

var dataObject = { 'apple': 1, 'banana': 2, 'orange': 3 };

// Save the object in local storage
localStorage.setItem('dataObject', JSON.stringify(dataObject));

// Get the object from storage
var receivedObject = localStorage.getItem('dataObject');

console.log('receivedObject: ', JSON.parse(receivedObject));

Answer №3

Utilizing HTML's localStorage and/or sessionStorage can be beneficial for passing values between pages. While these features are built into HTML, they require JavaScript for manipulation.

localStorage will permanently store any value you assign to it, whereas sessionStorage will only hold the value for a session - similar to the concept of cookies versus sessions in PHP. The syntax for both is identical.

To store values, you can use this syntax:

localStorage.setItem(key, value);

Where 'key' is your identifier and 'value' is the data you want to store. To retrieve the stored value, you can use:

localStorage.getItem(key);

This allows you to store a value on one page using `setItem` and retrieve it on another page using `getItem`.

Here are a few important points to consider:

  • Consider the longevity of your data.

  • Since localStorage retains data indefinitely (unless manually deleted or cleared by the browser), consider whether sessionStorage would suffice in certain cases.

  • localStorage functions as a universal JavaScript object.

  • Rather than using getter and setter methods, you can directly access and modify properties if desired. For example, `localStorage.key = value;` (setter) or `var x = localStorage.key;` (getter).

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

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

Enhancing the JQuery Dialog box by assigning an ID to the standard close button ("X") icon

Is there a method to instruct JQuery to assign an id to the default close "X" link widget (located at the top right of the dialog window in the header bar) when initializing the dialog? I am aware that you can assign an ID to the OK/Cancel buttons by spec ...

What is the best way to capture any internal errors that may arise from external JavaScript code?

Within a JavaScript file, I am utilizing an API call (an npm module in Node.js) and aiming to gracefully handle any errors that may arise. However, if I input a faulty API-KEY or a non-existent city name, the internal code of the API generates an error tha ...

Selenium testing - Immediate disappearance of OK/Cancel popup

Something strange is happening here. When I manually test this, I click the delete button, wait for the popup to appear https://i.sstatic.net/6PMS4.png and then click OK to remove the record successfully. However, when I attempt the same process in Java/Se ...

Upon first render, useSession from Next Auth does not retrieve the session

I am currently working on a project to create a website using NextJS v13 and Next Auth v4. However, I have encountered an issue where the session is not returned in the initial render when utilizing the useSession hook. As a result, several components are ...

Pressing anywhere will close the MagnificPopup ajax box

Every time I attempt to fill out the login form (which appears as a magnificent pop-up AJAX box), it unexpectedly closes with just one click. main.html $(document).ready(function() { $('.ajax-popup-link').magnificPopup({ ...

What could be the reason for the ReferenceError that is being thrown in this code, indicating that '

let number = 1; console.log(number); Feel free to execute this basic code snippet. You may encounter an issue: ReferenceError: test is not defined, even though the variable was declared. What could be causing this unexpected behavior? ...

Create a "load additional data" button

I'm working on building my blog and I've run into a roadblock while trying to implement a load more button. Here's what I currently have: actions: { LOAD_ARTICLE_LIST: function ({ commit }) { axios.get('someurl/articles') ...

What is the best way to create a for loop that collects all the weekdays falling between two specific months?

My current task involves gathering all the days of the week from Sunday to Saturday, starting with the actual date. I started working on a code that uses a for loop to push each day into an array. However, I encountered a problem with weeks that span acros ...

properly referencing files

I'm having trouble referencing the correct files in my c9 project: The first issue is with a picture I want to reference. This is what my current code looks like: <img src="pic1.jpg" class="d-block w-100" alt="...">. Here is my folder structu ...

What is the best way to ensure that the same object is not selected multiple times when executing concurrent queries

Currently, I am developing a delivery service that processes 8 orders simultaneously, each requiring a unique consignment number to be stored in the database. However, due to the concurrent nature of the operations, the system is assigning the same object/ ...

What is the method for accessing the AG-Grid Grid API beyond the Vue component?

In my application, I have a component called Home and another one called AgGrid. The AgGrid component is displayed within the Home component, containing the actual AG-Grid. Here's how the Home component is structured: <template> <AgGrid :ro ...

Tips for extracting a portion of a string in JavaScript:

I'm dealing with a string that looks like this: var str1="tag:youtube.com,2008:video:VrtMalb-XcQ"; I want to extract the last part of the string, which is VrtMalb-XcQ. What's the best way to do this? ...

Can the z-index of a div be altered by a checked checkbox?

I've been trying to figure out how to make a PayPal button only clickable after the user confirms the Terms of Service. My idea is to place another div over the PayPal button with an unchecked checkbox, opacity, and z-index. When the user checks the c ...

Spacing between products in Woocommerce product list

Welcome to my website! Check it out here: I am facing an issue with a long margin at the bottom of my woocommerce product list. I have tried using CSS to change it as shown below: .woocommerce .products ul, .woocommerce ul.products { margin-bot ...

Expanding Vue Tabs with Bootstrap: Manipulating tab-content to perfectly fill parent height

On my webpage, I have implemented a tabs component called b-tabs. This component is enclosed within a parent div with a specific height. I am trying to make the content of the tabs take up the full remaining height of the parent component. https://i.ssta ...

Arranging items by specific criteria in ng-repeat for a personalized sorting experience

Within my controller, I have an object named $scope.addresscards. The JavaScript code is provided below: var myApp = angular.module('myApp', []); function MyCtrl($scope) { $scope.addresscards = { "work_address": { "location":"w ...

What is the best way to save data in Next.js so that it can be accessed from any location

I am working on a Next.js application where I need to make API requests based on user inputs. To do this, I want to generate a token at the beginning of the app and whenever necessary based on user data from getServerSideProps or a similar method. After ex ...

Error in JQUERY: Uncaught TypeError - Index Of Error

My goal is to hide certain rows in my table when a button is clicked, using JQuery. I have successfully implemented the following script (with the commented line intact). <button href="#" id="axthis" style="text-decoration:none" target="_blank" class= ...