Home > database >  How do I create elements on a new html page, based on selected data from another html page?
How do I create elements on a new html page, based on selected data from another html page?

Time:09-29

I'm creating a web application (html.css.js) where one can book a trip by boat. On page 1 there is a form with the option to select the amount of passengers. One page 2 I what to display the amount of selected passengers where each has an individual tag/element. When a passenger is selected a pre made html registration form is to be displayed. How do I send the value selected on page 1 to page 2 and generate the individual registration forms according to the selected value?

CodePudding user response:

You can simply save the value from the form to sessionStorage in JS. Then access the value by looking up the key in the sessionStorage. But remember that the user data will be lost as soon as the browser closes. If you want to keep that data, use localStorage or cookies.

// Save the information the user entered or clicked
    sessionStorage.setItem('key', 'value');
// Get the saved data from the client (browser)'s sessionStorage
    let userData = sessionStorage.getItem('key');
// Then in your new page pass the userData to your html

CodePudding user response:

There are 2 ways to do this without tempering with a server:

  1. When a user selects an option on page one, you can either store that option to a localStorage, and then get it in the next page.
  2. The other option is to make a query-parameter(in this case i do not know the framework you are using), but regardless, the query-parameter for the link that sends the user to the next page should be in this form: /second-page-name?the-option-key-or-name=the-value-user-select. Then in the second page, you can use the new URLSearchParams constructor to get the user option via the query params. In react you get that as a property of the Router, in pure JS, you contsruct your location through new URLSearchParams and then use the get method to get the value.

CodePudding user response:

since your current scenario dont have any security concern you can use sessionStorage to preserve user inputs to show later on other part of your site anytime in this manner

var dataToBeSend = {name:"someone",age:0,city:"any"}
// on page one
sessionStorage.dataFromPage1 = JSON.stringify(dataToBeSend)
// on page two
var data = JSON.parse(sessionStorage.dataFromPage1)

updated answer inspired by @Jade since its even more suitable

  • Related