Store and retrieve user input using JavaScript or JSON

Can someone please assist me in finding a solution to this problem? I have 3 input fields where users can type in their answers. There is also a "SAVE" button that allows users to download their input values into a file.txt. Additionally, there is a "choose file" button that enables users to load the values from the saved file back into the input fields.

Note: The saved file can be in any format, not necessarily ["111", "222", "333"].

function save_func() {
  var quest1 = document.getElementById("Question1").value;
  var quest2 = document.getElementById("Question2").value;
  var quest3 = document.getElementById("Question3").value;
  var data = [];
  data.push(quest1);
  data.push(quest2);
  data.push(quest3);
  var data_string = JSON.stringify(data);
  var file = new Blob([data_string], {
    type: "text"
  });
  var anchor = document.createElement("a");
  anchor.href = URL.createObjectURL(file);
  anchor.download = "MyProject.txt";
  anchor.click();
}

function load_func() {
  var file = document.getElementById("load").files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    var load = JSON.parse(reader.result)[0];
    document.getElementById("inputs").value = load;
  };
  reader.readAsText(file);
}
<form id="inputs">
  <label for="Question1">Question 1</label>
  <br />
  <input type="text" id="Question1" class="input-box" name="Question1name" /><br />
  <br />
  <label for="Question2">Question 2</label>
  <br />
  <input type="text" id="Question2" class="input-box" name="Question2name" /><br />
  <br />
  <label for="Question3">Question 3</label>
  <br />
  <input type="text" id="Question3" class="input-box" name="Question3name" /><br />
  <br />
  <button onclick="save_func()">Save</button> And To Load A Project <input id="load" type="file" value="load" onchange="load_func()">
</form>

Answer №1

There seems to be an issue in your code where the file is not being loaded back into the input fields on your page. The load_func function is trying to set the value of an input with the id of "inputs", which is a form and not an input. To fix this, you just need to load the values back into "Question1", "Question2", and "Question3".

function save_func() {
  var quest1 = document.getElementById("Question1").value;
  var quest2 = document.getElementById("Question2").value;
  var quest3 = document.getElementById("Question3").value;
  var data = [];
  data.push(quest1);
  data.push(quest2);
  data.push(quest3);
  var data_string = JSON.stringify(data);
  var file = new Blob([data_string], {
    type: "text"
  });
  var anchor = document.createElement("a");
  anchor.href = URL.createObjectURL(file);
  anchor.download = "MyProject.txt";
  anchor.click();
}

function load_func() {
  var file = document.getElementById("load").files[0];
  var reader = new FileReader();
  reader.onloadend = function() {
    var load = JSON.parse(reader.result);
    document.getElementById("Question1").value = load[0];
    document.getElementById("Question2").value = load[1];
    document.getElementById("Question3").value = load[2];
  };
  reader.readAsText(file);
}
<label for="Question1">Question 1</label>
<br />
<input type="text" id="Question1" class="input-box" name="Question1name" /><br />
<br />
<label for="Question2">Question 2</label>
<br />
<input type="text" id="Question2" class="input-box" name="Question2name" /><br />
<br />
<label for="Question3">Question 3</label>
<br />
<input type="text" id="Question3" class="input-box" name="Question3name" /><br />
<br />
<button onclick="save_func()">Save</button> And To Load A Project <input id="load" type="file" value="load" onchange="load_func()">

EDIT

A new code snippet has been provided below for working with any number of inputs/fields. Any input with the class input-box will be saved and loaded. This code snippet can be used as an alternative to the previous one for most real-world applications.

const _Save = () => {
  let data = [];
  document.querySelectorAll(".input-box").forEach(el => {
    data = [...data, el.value];
  });

  let file = new Blob([JSON.stringify(data)], {
    type: "text"
  });

  let a = document.createElement("a");
  a.href = URL.createObjectURL(file);
  a.download = "SavedData.txt";
  a.click();
}

document.querySelector("#load").addEventListener("change", e => {
  let reader = new FileReader();
  reader.onloadend = () => {
    let data = JSON.parse(reader.result);
    document.querySelectorAll(".input-box").forEach((el, i) => {
      el.value = data[i];
    });
  };
  reader.readAsText(e.target.files[0]);
});
<label for="Question1">Question 1</label>
<br />
<input type="text" id="Question1" class="input-box" name="Question1name" /><br />
<br />
<label for="Question2">Question 2</label>
<br />
<input type="text" id="Question2" class="input-box" name="Question2name" /><br />
<br />
<label for="Question3">Question 3</label>
<br />
<input type="text" id="Question3" class="input-box" name="Question3name" /><br />
<br />
<button onclick="_Save()">Save</button> And To Load A Project <input id="load" type="file" value="load">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connect a designated button to a designated modal for a seamless user experience

I am struggling to dynamically change the content of a modal based on different buttons being clicked. The issue lies in trying to reference the div element within JavaScript since I can't have multiple elements with the same ID. As a newcomer to JS, ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...

JavaScript element styling in a Partial view, experiencing issues with functionality

In the main view, the javascript element is working fine. However, in the partial view it seems to not be functioning even though it is correctly formatted. Any ideas on how to fix this issue? Check out this fiddle for reference: http://jsfiddle.net/bgrin ...

AngularJS - Viewless and Issue-Free

I'm currently working on a project that involves using AngularJS and PHP. I made some changes, but now it's not functioning properly... The issue is that there are no errors in the console, Angular works (I can retrieve its version), but my vi ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...

What is the method for creating a line break in text?

Here is some example code I have: <h3 class="ms-standardheader"> <nobr> Reasons for proposals selected and not selected </nobr> </h3> Now I also have an image to show. The problem is that my text appears too large, so I a ...

Strategies for sending data to child components in Vue

Within my parent component, I am making an API call and receiving a response. My goal is to pass this response as a prop to a child component in Vue. Below is the snippet of the parent component and the API call: <button class="btn button col-2&quo ...

Only apply prevent default on specific levels for better control

I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am st ...

Enhancing Connectivity Through Fastify and Fastify-HTTP-Proxy Integration

I'm currently utilizing fastify along with fastify-http-proxy on a VPS running Ubuntu 19.x that is equipped with three unique IPv4 addresses. I have confirmed the functionality of these IP addresses by testing them using the following example IPs: cur ...

Pulling the month name based on a specific year and week using Javascript

In my HTML form, there are two fields called Year and Week. When the user chooses a Year and Week from the dropdowns, I would like to show the corresponding Month Name for that specific year and week. Is there anyone who can assist me in retrieving the m ...

Adjust the appearance of "FAQS" to show as "FAQs" in Lodash

I've integrated the lodash library - a powerful JavaScript utility tool - into my AngularJS project. <div ng-repeat="question in questions"> <label>{{question | startCase}}</label> </div> If you want to learn more about th ...

Activate a timer as soon as the page is first loaded. The timer must continue running from the initial load even if the user leaves

Looking to implement a time-limited offer on the first stage of our checkout process. The timer should start at 5 minutes when the page loads and continue counting down even if the user leaves the page and returns. Has anyone come across a script that can ...

Challenges arise when using Bootstrap 4 for country selection

There have been reports that bootstrap 4 country select is not functioning properly. In an effort to troubleshoot, I delved into the documentation to find a solution. To make bootstrap-select compatible with bootstrap 4, refer to: Bootstrap 4 beta-2 ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Is there a way for me to replace zero with a different number dynamically?

Is there a way to dynamically insert a different number instead of zero in mongoose? displayCity: (req, res, next) => { let id = req.params.id; provinceAndCity.findById({ _id: id }).populate('city.0.limitation', 'title ...

elastic geolocation distance filtering with multiple coordinates

I am currently using version 1.5 of Elastic. Suppose I have this query from the Elastic documentation: { "filtered" : { "query" : { "match_all" : {} }, "filter" : { "geo_distance_range" : { ...

Utilize interpolation with ES6 and an Angular 1.4 directive

Currently experimenting with the unique ES6 + Angular combination and facing a challenge in interpolating an html string within a directive that includes scope bindings. We have attempted the following approach: Current scenario The code below is functi ...

Javascript downloadable content available for download

<div class="center"data-role="content" id="content" > <a href="#flappy" data-transition="slide" >Avoid Becoming a Terrorist</a> </div> <div id="flappy" > <center> <div id="page"> ...

Executing JavaScript function from external SVG file globally

I am working on an HTML page that includes an external JavaScript module <script type="text/javascript" src="js/js.js"></script> and also an external SVG map called "img/map.svg". My goal is to create clickable objects on the map that will t ...