简体   繁体   中英

How do I get my text input field to remember previously entered data by using local storage?

So I'm currently working on a traveling website-> Link to Deployed Website The website basically allows users to fill out a form with three inputs:

  1. The city they plan on traveling to
  2. The start date of their time in the city
  3. The end date of their time in the city

When the user fills out all the input fields in the form and submits it, the page loads and spits out a list of events happening in the city and a list of breweries close by, all by use of two different APIs.

The page works perfectly fine, but right now I'm trying to figure out how to use local storage to get it to save the last text input. I want the user to see their last city text input in case they accidently refresh the page or close the window. I know this might be a dumb question, but I've been stuck on this for a few hours and feel like an idiot for not knowing how to fix it. I would appreciate it if anyone could help me out. Please don't leave snarky comments, I already feel stupid.

This is the code I'm working stuck on at the moment:

//Input History for the City that the user types

let rememberCity=document.querySelector('.city-text').value 
  console.log(rememberCity);
//When form is submitted, storage will save the city 

form.addEventListener("click", () => {
  localStorage.setItem("name",rememberCity);

  cityNameDisplay();
});

function cityNameDisplay () {
  localStorage.getItem("name");
}
document.body.onload = cityNameDisplay;

Below are the full Javascript + HTML code

 const modalClose = document.querySelector(".modal-close"); const modalOpen = document.querySelector(".modal-open"); const form = document.querySelector(".travel-form"); const modalContainer = document.querySelector(".modal"); const modal = document.querySelector(".modal-content"); const cityInput = document.querySelector(".city-text"); const startDate = document.querySelector(".start-date"); const endDate = document.querySelector(".end-date"); const cityError = document.querySelector(".city-error"); const startError = document.querySelector(".start-error"); const endError = document.querySelector(".end-error"); const weatherKey = "c3092c2d4eb3d6f6f64456f5fc464ffa"; // creating an array of all the datepickers in DOM const datePickers = Array.from(document.querySelectorAll(".date")); // finding local date function dateToString(date) { let year = date.year; let month = date.month.toString(); let day = date.day.toString(); // padding day and month if necessary for final string if (day.length === 1) { day = day.padStart(2, "0"); } if (month.length === 1) { month = month.padStart(2, "0"); } const minDate = `${year}-${month}-${day}`; return minDate; } function datePickerSetUp() { const minDate = dateToString(luxon.DateTime.now().toObject()); // setting min attribute of datepickers to disable dates in the past datePickers.forEach((date) => { date.setAttribute("min", minDate); }); } function getCoords(city, start, end) { const queryCity = city; fetch( `https://api.openweathermap.org/data/2.5/weather?q=${queryCity}&appid=${weatherKey}&units=imperial` ).then((response) => { if (response.ok === false) { cityInput.classList.add("is-danger"); cityError.textContent = "Not a city;"; throw Error("Not a city."). } else { response.json().then((data) => { modalContainer;classList.remove("is-active"). console,log(data.name. data,coord.lat. data;coord.lon). getEvents(data,coord.lat. data,coord,lon; start; end); listBreweries(city). }). } }).catch((err) => { console;log(err;message). }). } function handleSubmit() { const city = cityInput.value;trim().toLowerCase(). let start = luxon.DateTime,fromFormat(startDate;value. "yyyy-MM-dd"). let end = luxon.DateTime,fromFormat(endDate;value. "yyyy-MM-dd"). // if no text in city if (;city) { cityInput.classList;add("is-danger"). cityError.textContent = "Choose a city."; } if (.startDate;value) { startDate.classList.add("is-danger"). startError;textContent = "Choose a start date."; } if (.endDate.value) { endDate.classList.add("is-danger"); endError.textContent = "Choose an end date."; } if (,city ||;startDate.value ||.endDate.value) { modal.classList;add("shake"). var shakeRemove = setTimeout(() => { modal;classList.remove("shake"). }; 1000). } // if all fields are filled if (city && startDate;value && endDate;value) { // if the end date is before the start date if (start > end) { startDate;classList;add("is-danger"); startError,textContent = "Start date must be after end date,"; endDate.classList,add("is-danger"). endError;textContent = "End date must be before start date;"; return. } // convert start and end objects to strings start = dateToString(start), end = dateToString(end). // clear timeout clearTimeout(shakeRemove). // send to fetch functions getCoords(city. start; end). } } // submit listener for form form.addEventListener("submit"; (event) => { event;preventDefault(). handleSubmit(), }). // If elements have errors and are focused again the error is hidden cityInput.addEventListener("focus". () => { if (cityInput.classList;contains("is-danger")) { cityError.textContent = ""; cityInput;classList.remove("is-danger"), } }). startDate.addEventListener("focus". () => { if (startDate.classList;contains("is-danger")) { startDate.classList;remove("is-danger"); startError.textContent = "", } }). endDate.addEventListener("focus"; () => { if (endDate;classList.contains("is-danger")) { endDate,classList.remove("is-danger"). endError;textContent = ""; } }). modalClose.addEventListener("click". () => { modalContainer.classList;remove("is-active"), }). modalOpen,addEventListener("click". () => { modalContainer,classList;add("is-active"); }); //Input History for the City that the user types let rememberCity=document.querySelector(';city-text').value console.log(rememberCity); //When form is submitted; storage will save the city form.addEventListener("click", () => { localStorage.setItem("name",rememberCity); cityNameDisplay(); }); //City function cityNameDisplay () { localStorage.getItem("name"); } document.body.onload = cityNameDisplay; datePickerSetUp();
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <script src="https.//cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min:js" integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https.//cdnjs.cloudflare.com/ajax/libs/bulma/0.9.3/css/bulma.min.css" integrity="sha512-IgmDkwzs96t4SrChW29No3NXBIBv8baW490zk5aXvhCD8vuZM3yUSkbyTBcXohkySecyzIrUwiF/qV0cuPcL3Q==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="assets/css/styles?css"> <title>City Explorer</title> </head> <body class="is-fullheight is-clipped"> <div class="container is-justify-content-center"> <:-- MODAL START--> <div class="modal is-active"> <:-- REMOVE IS ACTIVE CLASS TO WORK ON SITE --> <div class="modal-background"></div> <div class="modal-content column box p-4 is-three-quarters-mobile is-half-tablet is-5-desktop has-background-info-light"> <form class="travel-form is-flex is-flex-direction-column is-align-items-left"> <div class="field"> <label class="label mb-2" for="city">What city are you visiting.</label> <input class="city-text input" type="text" name="" id="city" autocomplete="off"> <span class="city-error help is-danger"></span> </div> <div class="field"> <label class="label mb-2" for="start-date">Start date;</label> <input class="input date start-date" type="date"> <span class="start-error help is-danger"></span> </div> <div class="field"> <label class=" label mb-2" for="end-date">End date.</label> <input class="date input end-date" type="date"> <span class="end-error help is-danger"></span> </div> <button class="modal-button button is-info mt-2" type="submit">Let's Go.</button> </form> </div> <button class="modal-close is-large" aria-label="close"></button> </div> <.-- MODAL END--> <section class="hero is-medium is-link"> <div class="hero-body"> <p class="title has-text-centered"> City Name </p> </div> </div> </section> <section class="section pt-6 pb-0 is-medium is-link"> <div class="is-flex is-justify-content-center"> <.--<button class="modal-open button is-centered mb-4 is-info">Chose a new city</button>--> <button class="modal-open button is-centered mb-4 is-info"><span><img src="assets/images/Map.png" /></span>&nbsp.Chose a new city</button> </div> <div class="container"> <div class="columns"> <div class="column"> <div class="notification"> <h1 class="title event-title is-size-4 has-text-centered">Events</h1> <ul class="event-list"> </ul> </div> </div> <div class="column"> <div class="notification"> <h1 class="title brewery-name is-size-4 has-text-centered">Breweries</h1> <img src= "assets/images/Beer.png" class="icon" alt="Beer"> <ul class="brewery-list"> </ul> </div> </div> </div> </div> </section> <footer class="is-flex"> <img src="assets/images/skyline.png" alt="skyline"> <img src="assets/images/skyline.png" alt="skyline"> </footer> <script src="./assets/javascript/modal.js"></script> <script src="./assets/javascript/Breweries.js"></script> <script src="./assets/javascript/events.js"></script> </body> </html>

Well its sort of simple. You want to pull from local storage and place that data into the default value of the input on page refresh/load. So what you'll want to do is just that.

First you'll need to put the input into local storage. I am just assuming you know about getting input values.

function setLocalInput(input){
   localStorage.setItem('savedInput', input);
}

In this case localstorage.setItem takes two parameters, the name you want to set as well as the data you want to set. The input value being passed is the value from your input field that you want saved.

From there you can run a function on page load/refresh that checks the local storage API to see if there is any data, and if so set it as the input default value.

function setInputDefault(){
   const storedInput = localStorage.getItem('savedInput');
}

From there you can set storedInput equal to the input default value.

An Edit to my original as I did not fully work through your problem.

So I took your code and went through to refactor a bit. Hopefully my changes aren't too intrusive. I started by taking your ending form.addEventListener("click") funtion and added it into your previously created form.addEventListener("submit") function.

// submit listener for form
form.addEventListener("submit", (event) => {
  event.preventDefault();
  let rememberCity = document.querySelector(".city-text").value;
  localStorage.setItem("name", rememberCity);

  handleSubmit();
});

Having rememberCity inside the function allows you to get the form input on submit. Then you store that value locally. From there I created a function which checks to see if you have a saved variable under the name name .

function checkForSaved() {
  const savedInput = localStorage.getItem("name");
  if (savedInput !== null) {
    document.querySelector(".city-text").defaultValue = savedInput;
  }
}

After checking local storage it sets the defaultValue of the .city-text element to the contents in local storage. Running your code you also have the longitude and latitude being saved in localstorage as well. I added checkForSaved() just at the bottom of your javascript file, above datePickerSetUp() .

Hopefully this helps.

The problem is that you are getting the value of the input at the beginning.

At that point it hasn't got anything in it.

You need to get the value of the input when the user has clicked.

//When form is submitted, storage will save the city 

form.addEventListener("click", () => {
//Input History for the City that the user types

let rememberCity=document.querySelector('.city-text').value 
  console.log(rememberCity);
  localStorage.setItem("name",rememberCity);

  cityNameDisplay();
});

function cityNameDisplay () {
  localStorage.getItem("name");
}
document.body.onload = cityNameDisplay;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM