You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML单选按钮选中状态本地保存为TXT并恢复选中状态

HTML表单文本框与单选按钮状态本地保存/修复方案

问题说明

  • 开发的HTML表单包含文本输入框和单选按钮组(name="Month")
  • 现有脚本可将文本框内容保存到本地TXT并加载,但加载时单选按钮状态未正确恢复,反而将选中值填充到不存在的文本框中
  • 已能通过document.querySelector('input[name="Month"]:checked').value获取单选按钮选中值,但加载逻辑有误

修改后的完整代码

JavaScript 部分

var separator = "_*_";
// 单独维护文本框ID列表
var textBoxIds = ["inputTextToSave1", "inputTextToSave2"];
// 单选按钮组的name
var radioGroupName = "Month";

function saveTextAsFile() {
  var textToSave = "";
  // 收集文本框内容
  textBoxIds.forEach(function(id, index) {
    textToSave += document.getElementById(id).value;
    // 非最后一项加分隔符
    if (index !== textBoxIds.length - 1) {
      textToSave += separator;
    }
  });
  // 收集单选按钮选中值并添加到末尾
  var radioState = document.querySelector(`input[name="${radioGroupName}"]:checked`).value;
  textToSave += separator + 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];
  if (!fileToLoad) return;

  var fileReader = new FileReader();
  fileReader.onload = function(fileLoadedEvent) {
    var textFromFileLoaded = fileLoadedEvent.target.result;
    var dataArray = textFromFileLoaded.split(separator);
    
    // 恢复文本框内容
    textBoxIds.forEach(function(id, index) {
      if (dataArray[index]) {
        document.getElementById(id).value = dataArray[index];
      }
    });
    
    // 恢复单选按钮选中状态
    var savedRadioValue = dataArray[textBoxIds.length];
    if (savedRadioValue) {
      var targetRadio = document.querySelector(`input[name="${radioGroupName}"][value="${savedRadioValue}"]`);
      if (targetRadio) {
        targetRadio.checked = true;
      }
    }
  };
  fileReader.readAsText(fileToLoad, "UTF-8");
}

HTML 部分

<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 colspan="3">
      <label><input type="radio" id="id_june" name="Month" value="June" checked="checked" /> June</label>
      <label><input type="radio" id="id_december" name="Month" value="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>

关键修改点

  • 拆分文本框和单选按钮的维护逻辑,避免将单选按钮组name误当作文本框ID
  • 保存时分别收集文本框内容和单选按钮选中值,统一用分隔符拼接
  • 加载时拆分数据后,单独处理文本框内容恢复和单选按钮选中状态设置
  • 增加基础空值判断,避免加载时出现错误

内容的提问来源于stack exchange,提问作者Allen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 09:40:41