简体   繁体   中英

Add multiple values to localStorage and then retrieve a random one in JavaScript

I am trying to make a system where the user inputs multiple values at separate times and then can click a button that tells them one of their inputs (at random). This is what I have so far:

(Note: for some odd reason this code snippet is not functioning properly here (at least not on my side) but it is working just fine in JS Bin and even my own Notepad++)

 function store(){ var toStore = document.getElementById("itemInputBox"); localStorage.setItem("itemInputBox", toStore.value); } function get(){ var toGet = localStorage.getItem("itemInputBox"); document.getElementById("outputArea").innerHTML = toGet; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <form id="itemForm"> <input type="text" id="itemInputBox" autocomplete="off" onmouseout="store()"><br><br> <button id="getStoredValue" onclick="get()" type="button" style="cursor:pointer;">Get Input Value</button> </form> <div id="outputArea"></div> </body> </html>

As I am fairly new to coding (have been doing it for only a year or so) and I am also new to localStorage, I need some guidance for this. Thanks to whoever responds!

You can use an array to store your values
Before you add a new value you'll have to retrieve the array from local storage
Add the new value to the array and replace the previous array in local storage with the updated one
Use JSON to serialize the data to store it in local storage If there is no data in local storage create an array with the value

For the get functionality, after you retrieve the array you can generate a random number from 0 to the length of the array-1 to choose a value by index.

You can use Arrays in Javascript to store multiple values in the localStorage. When storing the values, they should be in JSON format. Also, when retrieving the values you have to pass that JSON string to `JSON.parse(array) and then retrieve the values.

To get a random value from that array, you can use Math functions in JavaScript. Please check the example below. It won't work in the StackOverflow code snippets section because it restricts the LocalStorage functions but you can check it locally.

 function store(){ var toStore = document.getElementById("itemInputBox"); var valuesJSON = get(); if (valuesJSON == null){ createLocalStorageKey(); } var values = JSON.parse(get()); values.items.push(toStore.value); localStorage.setItem("itemInputBox", JSON.stringify(values)); } function createLocalStorageKey(){ localStorage.setItem("itemInputBox", JSON.stringify({items:[]})); } function get(){ var toGet = localStorage.getItem("itemInputBox"); return toGet; } function parseValueToHTML(){ var valuesJSON = get(); if (valuesJSON == null){ createLocalStorageKey(); } var values = JSON.parse(get()); document.getElementById("outputArea").innerHTML = values.items[Math.floor(Math.random() * values.items.length)]; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <form id="itemForm"> <input type="text" id="itemInputBox" autocomplete="off"><br><br> <button onclick="store()" type="button">Store Value</button> <button id="getStoredValue" onclick="parseValueToHTML()" type="button" style="cursor:pointer;">Get Input Value</button> </form> <div id="outputArea"></div> </body> </html>

my way...

 const itemForm = document.forms['item-form'] , getAllItems = _ => { let r = localStorage.getItem('itemInputBox') return !r ? [] : JSON.parse(r) } , setAllItems = arr => { localStorage.setItem('itemInputBox',JSON.stringify(arr)) } ; itemForm.setValueStored.onclick=()=> { let val = itemForm.itemInputBox.value.trim() if (val) { let store = getAllItems() if (!store.include(val)) { store.push(val) setAllItems(store) } } itemForm.itemInputBox.value = '' } itemForm.getStoredValue.onclick=()=> { let store = getAllItems() itemForm.itemInputBox.value = (!store.length) ? '' : store[Math.floor(Math.random() *store.length)] }
 <form name="item-form"> <input type="text" name="itemInputBox" autocomplete="off"> <br><br> <button name="setValueStored" type="button">Set value in store</button> <button name="getStoredValue" type="button">Get random input value from store</button> </form>

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