0

I would just like to start by saying I am very new to HTML so forgive the poor code structure and lack of knowledge.

I have created a form in which the user fills out a few details about their daily exercises, the name of the log entry, name of exercise etc.. I then use some java functions to store these values and then on a separate page I want to display these values back to the user in a textbox format. My issue is I want to display all the values inside 1 textbox, but I do not know how to read them out in this format.

This is the HTML where I create and save the user input:

 <!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Add New Log</title>
  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">

  <link rel="stylesheet" href="CSS/New Log.css">
  <script src="JavaScript/New Log.js"></script>

</head>

<body>
<script type = "text/JavaScript">
function save() {
    // save values into localStorage
    localStorage['input1'] = document.getElementById('eName').value;
    localStorage['input2'] = document.getElementById('exercise').value;
    localStorage['input3'] = document.getElementById('date').value;
    localStorage['input4'] = document.getElementById('sTime').value;
    localStorage['input5'] = document.getElementById('eTime').value; 
    localStorage['input6'] = document.getElementById('cal').value;  
    alert("Log Entry Saved");
};


</script>

<h1> Add New Log </h1>

<form id="contact-form">
        <label for="name">Log entry name:</label>
        <input type="text" id = "eName"  value="" placeholder="Run at the 
park"/>
       <label for="email">Name of exercise:</label>
        <input type="name" id = "exercise"  value="" placeholder="Jogging"  />
        <div id="line">
         <label> ------------------------------ <span class="required">
</span></label>
         </div>
         <div id="detail">
        <label for="telephone">Date: </label>
        <input type="number" id = "date" value="" />
        <label for="telephone">Start Time: </label>
        <input type="number" id = "sTime"  value="" />
        <label for="telephone">End Time: </label>
        <input type="number" id = "eTime" value="" />
        <label for="telephone">Calories Lost: </label>
        <input type="number" id = "cal"  value="" />
       </div>


</form>

<li><a href="Fitness Log.html" onclick ="save()"> Add New Log</a></li>




</body>


</html>

Here when the add new log button is clicked, the user information is stored.

This is where I want to load the information inside just 1 textbox:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Health and Fitness</title>
  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">

  <link rel="stylesheet" href="CSS/Log.css">


</head>

<body>
<script>


window.onload = function(){
      var val = localStorage.getItem('input1'); // or localStorage.value


      if(val == null)
          val = "First try";

     document.getElementById("textbox").value = val;

}
</script>


<h1> Fitness Log </h1>
<p> Fitness Log keeps track of the exercise you complete and saves it to 
your account.</p> 

<div>
<ul>
    <li><a href="New Log.html"> Add Log</a></li>
    <li><a href="#"> Delete All</a></li>
</ul>
</div>


<input type="text" id = "textbox" value = "change"> </input>
<input type="text" id = "textbox2" value = "change"> </input>

</body>
<script>

</html>

I know I can load all this information from the user in separate text boxes, but I want to load all of it, not just input1 into the textbox. I don't know if this is the best way to do this, if there is a better way please let me know.

George Brooks
  • 199
  • 2
  • 17

3 Answers3

1

As you already mentioned you are just getting input1 value only and displaying it. If you want to display all of the values in single textbox, you will need to fetch them sepaartely from localStorage and then join them together and set the final value to the textbox.

var val1 = localStorage.getItem('input1');
var val2 = localStorage.getItem('input1');
var val3 = localStorage.getItem('input1');
...

In a similar manner, get all the values. I am assuming all of them are string. In that case you can just concat them to make a final value. Like:

var finalValue = val1.concat(val2).concat(val3);

and then

document.getElementById("textbox").value = finalValue;

This should give you desired results. Although I am not aware of your use case , but still this doesn't seem a good way of doing things. Rather, if you wish to save all this data, you might want to club the entire data into a single object in few properties and finally you can push this entire obj to localStorage like:

<script>
window.onload = function(){

var objToSave = {};

}

function save(){
    objToSave.data1 = document.getElementById('eName').value;
    objToSave.data2 = document.getElementById('exercise').value;
    ....
localStorage.setItem('objToSave', JSON.stringify(objToSave));  //you need to stringify object before pushing to localStorage

}

</script>

and when you get it back do something like:

var myDataFromLS = JSON.parse(localStorage.getItem('objToSave'));

Now this object contains all your input data but in a map kind structure. So you again need to pull different properties and bind them like explained above. The good point here is you can run a loop in the object and concat all values at once.

var finalValue= "";
for( var data in myDataFromLS ){
 finalValue= joinedString.concat(myDataFromLS[data]);
}

Now you can bind this string to text box using:

document.getElementById("textbox").value = finalValue;

This will help you keep your code a bit compact.

P.S. This is just based on your current implementation. Ofcourse there are better way of doing things.

Saurabh Tiwari
  • 4,632
  • 9
  • 42
  • 82
  • The first part of the code you gave worked to what I asked for Thank you for that, the second part for some reason just did not work. However, I will ask that I want to develop this code further to where I do not overwrite the user's input and instead, each time they create a new log, the previous entry is not overwritten and the new entry is displayed in a different textbox (or list in the future). Is my current approach easily adaptable to this kind of functionality? – George Brooks Apr 30 '17 at 14:03
  • The second part sets and gets a object from LS. This obj contains all your data. So once you get it back from LS as I mentioned in my answer, to set it into textbox you will have to pull properties out of it like, `myDataFromLS.data1` and then bind it to textbox – Saurabh Tiwari Apr 30 '17 at 14:06
  • For your use case the object model I suggested will be a good idea. Because that way you can go on making as many properties on your object as you want, while keeping the previous properties intact too. – Saurabh Tiwari Apr 30 '17 at 14:07
  • I added more data to the answer. May be it will help you use the second part of my answer – Saurabh Tiwari Apr 30 '17 at 14:12
  • I implemented this the same way you have explained, but the value of my textbox is not changing to the user input. – George Brooks Apr 30 '17 at 14:15
  • Are you getting the object back from LS. Does it contain the data – Saurabh Tiwari Apr 30 '17 at 14:16
  • I retrieve the LS the way you have shown but I do not believe the information is being saved when I click the add new log button, I believe this because the alert method does not even get called when I implement the objToSave.data1 approach of saving information. – George Brooks Apr 30 '17 at 14:18
  • I assume you made changes to your save method. If not, change it to `function save() { localStorage.setItem(JSON.stringify(objToSave)); }`. If you have already done this, try debugging or look for any errors in console. That might help – Saurabh Tiwari Apr 30 '17 at 14:48
  • After debugging I got this error Uncaught ReferenceError: objToSave is not defined at window.onload (Fitness Log.html:22) – George Brooks Apr 30 '17 at 14:51
  • @SaurabhTiwari `localStorage.setItem(JSON.stringify(objToSave))` sets `JSON` as key, does not set a value. – guest271314 Apr 30 '17 at 14:54
  • Thanks fr your observation @guest271314. I will change it – Saurabh Tiwari Apr 30 '17 at 14:55
  • @GeorgeBrooks: Your error indeed is valid. I missed defining the obj before using it. So on `window.onload` try defining the `objToSave` object. – Saurabh Tiwari Apr 30 '17 at 14:58
1

There is nothing wrong with your approach if you don't plan on adding more fields. The only issue you will encounter is, the more fields you add, the more changes your will make in several places. So a smarter approach could be either using jQuery to grab all form values or use plain javascript to grab all form values, both works well. You can look at this SO answers if you plan on using either jQuery or Java Grab form values with jQuery or JavaScript

After which you can then save in localstorage.

Community
  • 1
  • 1
theterminalguy
  • 1,842
  • 18
  • 20
1

You can use Object.entries(), += operator to concatenate localStorage key and value to .value of <input> element

var values = document.getElementById("textbox");
for (let [key, prop] of Object.entries(localStorage)) {
  values.value += ` ${key} : ${prop} `;
};
guest271314
  • 1
  • 15
  • 104
  • 177
  • I tried to implement your solution and it does work very well, for the most part, however, the textbox is filled with other information I do not want , Entry Name : ggff Exercise : dfege array : ["input1","input2"] input1 : yyyy input2 : ttttt input3 : input4 : input5 : input6 : pageLoadCount : 2. Where it says array, i do not wish to display that information after – George Brooks Apr 30 '17 at 15:05
  • @GeorgeBrooks You can remove ` ${key} : ` portion from `javascript` at Answer if `localStorage` property name should not be concatenated, leaving `values.value += prop;`. Do you mean that you do not want to set property `"array"` of `localStorage` at `.value` of `` element? – guest271314 Apr 30 '17 at 15:12
  • I am very confused because I did not change the previous code but it is now doing what I wanted. I did not change for (let [key, prop] of Object.entries(localStorage)) { values.value += ` ${key} : ${prop} `; }; But it is now not displaying the array part. – George Brooks Apr 30 '17 at 15:28
  • `"array"` should not be displayed. No property of `localStorage` is set to `"array"` – guest271314 Apr 30 '17 at 15:31
  • Yeah it is not now but originally it was, but now it has corrected itself? im not sure but I have made some of my own changes to your code and it does perform the functionality I want at this time. I will accept your answer thank you very much and if you have any advice on how to not overwite the previous entry in local storage (Make seperate local storage keys) so the user can make many log entries that would be helpful thank you. – George Brooks Apr 30 '17 at 15:33
  • No, the code did not correct itself. Earthling intervention is required. You can try and reproduce `javascript` which sets and gets `localStorage` at plnkr https://plnkr.co. You can increment the numerical portion of last property name `var lastKey = Math.max.apply(Math, Object.keys(localStorage).map(n => parseInt(n))); localStorage("input" + (lastKey + 1), "value")` – guest271314 Apr 30 '17 at 15:39