C. Yee C. Yee - 3 months ago 20
Javascript Question

Best practice for displaying items in localStorage in html.erb file

I have an array of items in localStorage that I want to display in my index.html.erb file. I'm using rails for this application. Should I send the information to my rails controller and then send it to my index.html.erb or is there a way to do it without sending the info to the controller? I rather not save the information on the server side.

Here's my code in my index.html.erb

<div id="result">
function storage(){
var items = JSON.parse(localStorage.getItem("cars"))
for (var i = 0; i < items.length; i++){
document.getElementById("result").innerHTML = items[i]

Right now this is showing just one item in the array in the view page instead of a number of items. If I do have to send the information to the controller first, how would I go about doing that? Any feedback would be greatly appreciated.

Answer Source

You are replacing the html every iteration so only the last item will be shown

Try something like:

document.getElementById("result").innerHTML += (items[i] + '<br>`);

Note: This assumes you are actually storing an array