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

Time:04-10

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 >
  
    <div >

        <!-- MODAL START-->

        <div >
            <!-- REMOVE IS ACTIVE CLASS TO WORK ON SITE -->
            <div ></div>
            <div
                >
                <form >
                    <div >
                        <label  for="city">What city are you visiting?</label>
                        <input  type="text" name="" id="city" autocomplete="off">
                        <span ></span>
                    </div>
                    <div >
                        <label  for="start-date">Start date:</label>
                        <input  type="date">
                        <span ></span>
                    </div>
                    <div >
                        <label  for="end-date">End date:</label>
                        <input  type="date">
                        <span ></span>
                    </div>
                    <button  type="submit">Let's Go!</button>
                </form>
            </div>
            <button  aria-label="close"></button>
        </div>

        <!-- MODAL END-->

    <section >
        <div >
            <p >
                City Name
            </p>
        </div>
    </div>
    </section>
    <section >
        <div >
           <!--<button >Chose a new city</button>--> 
            <button ><span><img src="assets/images/Map.png" /></span>&nbsp;Chose a new city</button>
        </div>
        <div >
            <div >
                <div >
                    <div > 
                        <h1 >Events</h1>
                        <ul >
                        </ul>
                    </div>
                </div>
                <div >
                    <div >  
                        <h1 >Breweries</h1>
                        <img src= "assets/images/Beer.png"  alt="Beer">
                        <ul >
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <footer >
       <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>

CodePudding user response:

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. Hopefully this helps you out a bit.

CodePudding user response:

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;
  • Related