reading and writing data to localStorage
With the load and clear buttons data is loaded or removed from localStorage. This data is used within the app to search for bus routes. See question: https://stackoverflow.com/questions/51574988/json-string-not-loading-data-into-local-storage
by roycode
HTML
<input type="button" value="Load route data" id="load">
<input type="button" value="Clear localStorage" id="clear">
<div id="local-storage-status"> </div>
<br>
<input type="text" id="search" placeholder="Enter route">
<input type="button" value="Find" id="submit"><br>
<p>Bus stop information:</p><hr>
<div id="result"></div>
JavaScript
/* Improvements:
* - Use localStorage.setItem()
* - No need to create a localStorage item for each bus route. LocalStorage can handle quite some data (depending on the browser and using local settings. See [What is the max size of localStorage values?](https://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values))
* - I'd simplify your data structure. Why put stops into an array and then an object? I've simplified this in my example.
* - When looping over times use for (var i = 0; i < data.Routes.length; i++) another alternative is to user .map when iterating over items within an array.
*/
const InitialBusScheduleData = {"Routes": [{"routeName": "Milledge","stops":{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}},{"routeName": "Orbit","stops":{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}},{"routeName": "East West","stops":{"Stop 1":"East Campus Deck","Stop 2":"Creswell Hall","Stop 3":"Hull St Deck","Stop 4":"Main Library","Stop 5":"Joe Frank Harris"}}]};
var BusSchdDataFromLocalStorage = [];
$(document).ready(function() {
const statusEl = document.querySelector('#local-storage-status');
const resultEl = document.querySelector('#result');
const data = JSON.parse(localStorage.getItem('routesInfo'));
if (data !== null) {
if (data.Routes.length > 0) {
BusSchdDataFromLocalStorage = data;
statusEl.innerHTML = 'localStorage data present';
} else {
statusEl.innerHTML = 'localStorage data absent';
}
}
// Store routes in localStorage when it is not present yet
// There's no need to store each stop in a separate localStorage. Unless your data goes over 5MB.
// See this discussion for more info: https://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values
const load = () => {
// access localStorage and save the...