I am a novice in the field of coding. Every time I try to put something in the prompt-box, it just saves the last string passed. In this case my command to end "done".
I already worked it out with a for loop and a function for saving the data. I am just lost on how it is not working with the while loop. Cause as far as I see, for and while are similar to each other, with the difference that a while loop doesn’t need a start-value and that you put the incrementation in the curly-brackets.
Ultimately I want to type in ‘Max’ and it should show on the next html-file, ‘Max’ and not ‘done’.
<!DOCTYPE html>
<html>
<head>
<title>dude</title>
<script type="text/javascript">
'use strict'
var i, Enter;
var dude=[];
</script>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript">
while (Enter!='done')
{
i++
if (dude[i]='done')
{
Enter=prompt("some text");
dude[i]=Enter
SaveData(dude[i]);
}
}
function SaveData()
{
localStorage.setItem("DATA", dude[i]);
}
</script>
</body>
</html>
2
Answers
So, you want to add repeated strings to local storage. Local storage is a key/value system.
At the moment you’re trying to assign each separate input value to the same key which is not giving you the desired outcome.
Since you want to capture each separate input somehow you might consider an array in which to store them. On each iteration of the loop (if the input value is not
done
) you can push the input value into an array.Once the iteration is complete (ie the input value is
done
) you canstringify
the array and assign that string to the local storagedata
key. (When you come to retrieve that data you would need toparse
that string back into an array.)In this example I’ve modified your code slightly with this aim in mind. The snippet doesn’t allow setting/getting data from local storage so I’ve logged the result of stringifying the array. As mentioned in the comments you can remove this line, and uncomment the next to get this working properly.)
(Addendum: you can see this working in this JSFiddle. Run the code example, and then open your dev tools to the "storage" tab, and look under "Local Storage -> h**tps://fiddle.jshell.net" and you’ll see your saved data.)
for reference :
Json Storage :
How do I store an array in localStorage?
Types of Loops :
https://www.tutorialrepublic.com/javascript-tutorial/javascript-loops.php
Localstorage :
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage