简体   繁体   English

如何使用本地存储让我的文本输入字段记住以前输入的数据?

[英]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.当用户填写表单中的所有输入字段并提交时,页面会加载并吐出城市中发生的事件列表和附近啤酒厂的列表,所有这些都是通过使用两个不同的 API 实现的。

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.我希望用户看到他们最后输入的城市文本,以防他们不小心刷新页面或关闭 window。我知道这可能是一个愚蠢的问题,但我已经坚持了几个小时,觉得自己像个白痴不知道如何修复它。 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以下是完整的 Javascript + HTML 代码

 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.在这种情况下, localstorage.setItem有两个参数,您要设置的名称以及您要设置的数据。 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 检查本地存储 API 以查看是否有任何数据,如果有则将其设置为输入默认值。

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

From there you can set storedInput equal to the input default value.从那里您可以将storedInput设置为等于输入默认值。

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.我开始使用您的结束form.addEventListener("click")函数并将其添加到您之前创建的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.在 function 中包含rememberCity允许您在提交时获取表单输入。 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 来检查你是否有一个名为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.检查本地存储后,它将.city-text元素的默认值设置为本地存储中的内容。 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() .我在 javascript 文件的底部添加了checkForSaved() ,在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使文本输入字段记住以前输入的数据 - Make text input fields remember previously entered data 如何验证我的输入字段以请求输入一些文本? - How do I validate my input field to request some text to be entered? 如何使用反应获取文本输入字段的值 - How do i get the value of text input field using react 如何使用 JavaScript 获取文本输入字段的值? - How do I get the value of text input field using JavaScript? 如何使用按钮将文本输入保存和显示到本地存储 - How do I save and show text input to local storage using a button 如何在范围滑块的幻灯片上将文本放入本地存储? - How do I get the text into local storage on slide of range slider? 如何通过使用本地存储来记住输入值? - how to remember inputs value by using local storage? 如何从本地存储中获取特定的ID数据,以便使用jquery在表单中进行编辑 - How do I get a particular Id data from local Storage for editing in form using jquery 如何根据在文本字段中输入的不匹配数字使 div 元素内的数字减少? - How do I get a number inside a div element to decrement based on an non matching number entered in text field? 如何从输入字段中获取数据到我的 ajax 请求中? - How do I get data from an input field into my ajax request?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM