Search code examples
javascripthtmlradio-button

How to locally save radio buttons selection status of HTML as .TXT file and load back the selection status


I am developing a simple html form to collect different users dataset using text input fields and radio buttons. After researching, I found a good piece of script to save to- and load from .txt file using two textbox fields as posted on this site at this link. I would like to build up on this script and add the state of (checked/unchecked) the following radio buttons:

<input type="radio" id="jan" name="Month" value="January" checked="checked" />
<input type="radio" id="dec" name="Month" value="December" />

Along with the var textboxes, the bellow variable saves the value of checked radio button but it loads the value back to a textbox rather than maintaining the checked state of the radio buttons

var radioState = document.querySelector('input[name="Month"]:checked').value;

I would appreciate any support on this

var separator = "_*_";
var textBoxes = ["inputTextToSave1", "inputTextToSave2", "Month"];

function saveTextAsFile() {
  var textToSave = "";
  for (var a = 0; a < textBoxes.length; a++) {
    textToSave += a < textBoxes.length - 1 ? document.getElementById(textBoxes[a]).value + separator : document.getElementById(textBoxes[a]).value + radioState;
  }
  var textToSaveAsBlob = new Blob([textToSave], {
    type: "text/plain"
  });
  var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
  var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

  var downloadLink = document.createElement("a");
  downloadLink.download = fileNameToSaveAs;
  downloadLink.innerHTML = "Download File";
  downloadLink.href = textToSaveAsURL;
  downloadLink.onclick = destroyClickedElement;
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);

  downloadLink.click();
}

function destroyClickedElement(event) {
  document.body.removeChild(event.target);
}

function loadFileAsText() {
  var fileToLoad = document.getElementById("fileToLoad").files[0];

  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent) {
    var textFromFileLoaded = fileLoadedEvent.target.result;
    var textesArray = textFromFileLoaded.split(separator);
    for (var a = 0; a < textBoxes.length; a++) {
      document.getElementById(textBoxes[a]).value = textesArray[a];
    }
  };
  fileReader.readAsText(fileToLoad, "UTF-8");
}
<table>
  <tr>
    <td>Text to Save:</td>
  </tr>
  <tr>
    <td colspan="3">
      <textarea id="inputTextToSave1" cols="80" rows="5"></textarea>
    </td>
  </tr>
  <tr>
    <td colspan="3">
      <textarea id="inputTextToSave2" cols="80" rows="5"></textarea>
    </td>
  </tr>
  <tr>
  <input type="radio" id="id_june" name="Month" value="June" checked="checked" />
<input type="radio" id="id_december" name="Month" value="December" />
  </tr>
  
  <tr>
    <td>Filename to Save As:</td>
    <td><input id="inputFileNameToSaveAs"></td>
    <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
  </tr>
  <tr>
    <td>Select a File to Load:</td>
    <td><input type="file" id="fileToLoad"></td>
    <td><button onclick="loadFileAsText()">Load Selected File</button></td>
  </tr>
</table>


Solution

  • Main changes:

    • Updated the saveAsTextFile function to include the value of your radio button
    • loadFileAsText function also now loads the radio button value
    • Removed month from textboxes array because it is handled separately

    Please note: The file will not save if you use the snippet execution below, you'll need to just drop this into a local html file and try it out.

        <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form with File Save and Load</title>
    </head>
    <body>
        <table>
            <tr>
                <td>Text to Save:</td>
            </tr>
            <tr>
                <td colspan="3">
                    <textarea id="inputTextToSave1" cols="80" rows="5"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <textarea id="inputTextToSave2" cols="80" rows="5"></textarea>
                </td>
            </tr>
            <tr>
                <td>Month:</td>
                <td>
                    <input type="radio" id="id_june" name="Month" value="June" checked="checked" />
                    <label for="id_june">June</label>
                    <input type="radio" id="id_december" name="Month" value="December" />
                    <label for="id_december">December</label>
                </td>
            </tr>
            <tr>
                <td>Filename to Save As:</td>
                <td><input id="inputFileNameToSaveAs"></td>
                <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
            </tr>
            <tr>
                <td>Select a File to Load:</td>
                <td><input type="file" id="fileToLoad"></td>
                <td><button onclick="loadFileAsText()">Load Selected File</button></td>
            </tr>
        </table>
    
        <script>
            var separator = "_*_";
            var textBoxes = ["inputTextToSave1", "inputTextToSave2"];
    
            function saveTextAsFile() {
                var textToSave = "";
                for (var a = 0; a < textBoxes.length; a++) {
                    textToSave += document.getElementById(textBoxes[a]).value + separator;
                }
                
                // Add the selected radio button value
                var selectedMonth = document.querySelector('input[name="Month"]:checked').value;
                textToSave += selectedMonth;
    
                var textToSaveAsBlob = new Blob([textToSave], {
                    type: "text/plain"
                });
                var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
                var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
    
                var downloadLink = document.createElement("a");
                downloadLink.download = fileNameToSaveAs;
                downloadLink.innerHTML = "Download File";
                downloadLink.href = textToSaveAsURL;
                downloadLink.onclick = destroyClickedElement;
                downloadLink.style.display = "none";
                document.body.appendChild(downloadLink);
    
                downloadLink.click();
            }
    
            function destroyClickedElement(event) {
                document.body.removeChild(event.target);
            }
    
            function loadFileAsText() {
                var fileToLoad = document.getElementById("fileToLoad").files[0];
    
                var fileReader = new FileReader();
                fileReader.onload = function(fileLoadedEvent) {
                    var textFromFileLoaded = fileLoadedEvent.target.result;
                    var textesArray = textFromFileLoaded.split(separator);
                    for (var a = 0; a < textBoxes.length; a++) {
                        document.getElementById(textBoxes[a]).value = textesArray[a];
                    }
                    
                    // Set the radio button based on the loaded value
                    var loadedMonth = textesArray[textesArray.length - 1];
                    document.querySelector(`input[name="Month"][value="${loadedMonth}"]`).checked = true;
                };
                fileReader.readAsText(fileToLoad, "UTF-8");
            }
        </script>
    </body>
    </html>