我有一个表格,如果提交表格,我希望两个收件箱值保留其值.

 // Function to save submitted values to local storage
  function saveSubmittedValues() {
    var supervisor = document.getElementById("supervisor").value;
    var substation = document.getElementById("substation").value;
    
    // Save submitted values to local storage
    localStorage.setItem("supervisor", supervisor);
    localStorage.setItem("substation", substation);
  }
 // Function to pre-fill dropdowns with saved values from local storage
  function prefillDropdowns() {
    // Retrieve saved values from local storage
    var supervisor = localStorage.getItem("supervisor");
    var substation = localStorage.getItem("substation");

    // Pre-fill supervisor dropdown
    if (supervisor) {
      document.getElementById("supervisor").value = supervisor;
    }

    // Pre-fill substation dropdown
    if (substation) {
      document.getElementById("substation").value = substation;
      // Trigger the onchange event of substation dropdown to populate parcels
      getParcels(substation);
    }
  }

// Call the setDefaultDate function when the page is loaded
window.onload = setDefaultDate;

function validateForm() {
  var isValid = true;
  var supervisor = document.getElementById("supervisor").value;
  var substation = document.getElementById("substation").value;
  var parcel = document.getElementById("parcel").value;
  var parcelId = document.getElementById("parcelId").value;
  var status = document.getElementById("status").value;
  var date = document.getElementById("datePicker").value;
  var comment = document.getElementById("comment").value;

  // Check if any field is null or blank
  if (!supervisor || !substation || !parcel || !parcelId || !status || !date || !comment) {
    document.getElementById("submit-message").innerText = "All fields must be filled.";
    return false; // Prevent form submission
  }

  // Save submitted values to local storage
  saveSubmittedValues();

  // Call prefillDropdowns function to update dropdowns with new values
  prefillDropdowns();

  // Disable form submit button to prevent resubmission
  document.getElementById("submit-button").disabled = true;

  return true; // Allow form submission
}

它会不断重置值,而不是将它们保留在本地存储中,以便在提交表单时填充回收件箱预览窗口.有什么 idea 我如何才能实现这一目标吗?

其余html代码:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
  <title>Daily Contact Form </title>
  <style>
    /* Your CSS styles here */
    body {
      font-size: 15px;
      background-color: #f0f8ff;
      font-family: Arial, sans-serif; /* Light blue background color */
    }
    .container {
      width: 50%;
      margin: 0 auto; /* Center the container horizontally */
      text-align: center; /* Center the content inside the container */
      padding-top: 20px; /* Add space at the top */
    }
    h1 {
      margin-top: 20px; /* Add space between header image and header text */
      font-size: 20px;
    }
    select {
      width: 50%; /* Set the width of dropdown menus to fill the container */
      font-size: 12px; /* Set font size for dropdown values */
      text-align-last: center; /* Align dropdown selections in the middle */
    }
    /* Additional styling to center-align dropdown selections */
    option {
      text-align: center;
    }
    textarea {
      height: 100px;
      width: 250px;
      font-size: 12px;
      width: 100%; /* Set font size for textarea */
    }
    input[type="submit"] {
      font-size: 12px; /* Set font size for submit button */
    }
    .submit-message {
      color: red;
      font-size: 12px;
    }
    .landowner-info {
      float: center;
      margin-top: 20px;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      background-color: #f9f9f9;
      width: 100%; /* Extend size of landowner info box */
    }
  </style>
  <script src="https://apis.google.com/js/api.js"></script>
  <script>

// Function to set the default date to today's date
function setDefaultDate() {
  var today = new Date();
  var day = today.getDate();
  var month = today.getMonth() + 1; // Months are zero indexed
  var year = today.getFullYear();

  // Format the date as YYYY-MM-DD for the input field
  var formattedDate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;

  // Set the default value of the date picker input field directly
  var datePicker = document.getElementById("datePicker");
  datePicker.setAttribute("value", formattedDate);

  // Set the value of the text box to the same date
  datePicker.value = formattedDate;
}


function updateMaxStatusAndLandownerInfo(parcelId) {
  updateMaxStatusForParcel(parcelId); // Call updateMaxStatusForParcel with the selected Parcel ID
  getLandownerInfo(parcelId); // Call getLandownerInfo with the selected Parcel ID
}

    function updateParcelInfo(landowner) {
      // Trigger search in "Raw Data" worksheet for landowner value
      google.script.run.withSuccessHandler(function(parcelIds) {
        var parcelIdDropdown = document.getElementById("parcelId");
        parcelIdDropdown.innerHTML = "";
        var option = document.createElement("option");
        option.value = "";
        option.text = "";
        parcelIdDropdown.appendChild(option);

        // Populate Parcel ID dropdown with matching rows from columns U3:U
        parcelIds.forEach(function(parcelId) {
          var option = document.createElement("option");
          option.value = parcelId;
          option.text = parcelId;
          parcelIdDropdown.appendChild(option);
        });
      }).getParcelIdsByLandowner(landowner); // Call server function to get matching parcel IDs
    }

function getLandownerInfo(parcel) {
  google.script.run.withSuccessHandler(function(landownerInfo) {
    document.getElementById("landowner-info-content").innerText = landownerInfo;
  }).getLandownerInfo(parcel);
}

    function getParcels(substation) {
      google.script.run.withSuccessHandler(function(parcels) {
        var parcelDropdown = document.getElementById("parcel");
        parcelDropdown.innerHTML = "";
        var option = document.createElement("option");
        option.value = "";
        option.text = "";
        parcelDropdown.appendChild(option);

        // Sort the parcel options alphabetically
        parcels.sort().forEach(function(parcel) {
          var option = document.createElement("option");
          option.value = parcel;
          option.text = parcel;
          parcelDropdown.appendChild(option);
        });

        // Update max status immediately after selecting parcel
        var selectedParcel = parcelDropdown.value;
        updateParcelInfo(selectedParcel);
      }).getParcels(substation);
    }

// Inside the updateMaxStatusForParcel function, where the status dropdown is being populated
function updateMaxStatusForParcel(parcel) {
  google.script.run.withSuccessHandler(function(maxStatus) {
    var statusDropdown = document.getElementById("status");
    statusDropdown.innerHTML = ""; // Clear previous options

    // Define status options in the desired order
    var statusOptions = ["", "Assigned to Agent", "Outreach", "Negotiating", "Pledged", "Signed", "Dropped"];

    // Add options to the dropdown in the defined order
    statusOptions.forEach(function(status) {
      var option = document.createElement("option");
      option.value = status;
      option.text = status;
      if (status === maxStatus) {
        option.selected = true; // Select the option if it matches the max status
      }
      statusDropdown.appendChild(option);
    });
  }).getMaxStatusForParcel(parcel);
}

  // Function to save submitted values to local storage
  function saveSubmittedValues() {
    var supervisor = document.getElementById("supervisor").value;
    var substation = document.getElementById("substation").value;
    
    // Save submitted values to local storage
    localStorage.setItem("supervisor", supervisor);
    localStorage.setItem("substation", substation);
  }
 // Function to pre-fill dropdowns with saved values from local storage
  function prefillDropdowns() {
    // Retrieve saved values from local storage
    var supervisor = localStorage.getItem("supervisor");
    var substation = localStorage.getItem("substation");

    // Pre-fill supervisor dropdown
    if (supervisor) {
      document.getElementById("supervisor").value = supervisor;
    }

    // Pre-fill substation dropdown
    if (substation) {
      document.getElementById("substation").value = substation;
      // Trigger the onchange event of substation dropdown to populate parcels
      getParcels(substation);
    }
  }

// Call the setDefaultDate function when the page is loaded
window.onload = setDefaultDate;

function validateForm() {
  var isValid = true;
  var supervisor = document.getElementById("supervisor").value;
  var substation = document.getElementById("substation").value;
  var parcel = document.getElementById("parcel").value;
  var parcelId = document.getElementById("parcelId").value;
  var status = document.getElementById("status").value;
  var date = document.getElementById("datePicker").value;
  var comment = document.getElementById("comment").value;

  // Check if any field is null or blank
  if (!supervisor || !substation || !parcel || !parcelId || !status || !date || !comment) {
    document.getElementById("submit-message").innerText = "All fields must be filled.";
    return false; // Prevent form submission
  }

  // Save submitted values to local storage
  saveSubmittedValues();

  // Call prefillDropdowns function to update dropdowns with new values
  prefillDropdowns();

  // Disable form submit button to prevent resubmission
  document.getElementById("submit-button").disabled = true;

  return true; // Allow form submission
}


    // Prevent form resubmission popup on page reload
    if (window.history.replaceState) {
      window.addEventListener("beforeunload", function () {
        window.history.replaceState(null, null, window.location.href);
      });
    }
  </script>
</head>
<body>
  <div class="container">
    <img src="https://i.imgur.com/16QsZja.png" alt="Header Image" style="width: 100%; max-width: 200px;">

    <h1>Daily Contact Form</h1>

    <form method="post" action="<?= getUrl() ?>" onsubmit="return validateForm()">
      <label>Land Agent</label><br>
      <select name="supervisor" id="supervisor">
        <option value=""></option>
        <option value="Dan">Dan</option>
        <option value="Ian">Ian</option>
        <option value="Parker">Parker</option>
      </select><br><br>

      <label>Substation</label><br>
      <select name="substation" id="substation" onchange="getParcels(this.value)">
        <option value=""></option>
        <? var subs = getDistinctSubstations(); ?>
        <? subs.sort().forEach(function(sub) { ?>
          <option value="<?= sub ?>"><?= sub ?></option>
        <? }); ?>
      </select><br><br>

      <label>Landowner</label><br>
      <select name="landowner" id="parcel" onchange="updateParcelInfo(this.value)">
        <!-- Parcel dropdown will be populated dynamically -->
      </select><br><br>

      <label>Parcel ID</label><br>
      <select name="parcelId" id="parcelId" onchange="updateMaxStatusAndLandownerInfo(this.value)">
        <!-- Parcel ID dropdown will be populated dynamically -->
      </select><br><br>

      <label>Status</label><br>
      <select name="status" id="status">
        <option value=""></option>
        <option value="Assigned to Agent">Passed to Agent</option>
        <option value="Outreach">Outreach</option>
        <option value="Negotiating">Negotiating</option>
        <option value="Pledged">Pledged</option>
        <option value="Signed">Signed</option>
        <option value="Denied">Denied</option>
      </select><br><br>

<label for="date">Date</label><br>
<input type="date" name="date" id="datePicker"><br><br>

      <label>Comment</label><br>
      <textarea name="comment" id="comment"></textarea><br><br>

      <input type="submit" name="submitButton" id="submit-button" value="Submit" />
      <span id="submit-message" class="submit-message"></span>
    </form>
<div class="landowner-info">
  <h2>Landowner Info</h2>
  <p id="landowner-info-content"></p> <!-- Display landowner information -->
</div>
  </div>
</body>
</html>

推荐答案

validateForm中删除prefillDropdowns();,因为您正在提交表单,但此时尚未重新加载.然后,更改您对window.onload = setDefaultDate;的命令

window.onload = function() {
    setDefaultDate();
    prefillDropdowns();
};

确保测试过程中没有出现错误,然后它应该工作.

Javascript相关问答推荐

如何通过onClick为一组按钮分配功能;

可以的.是否可以在不预编译的情况下使用嵌套 Select 器?

使用AJX发送表单后,$_Post看起来为空

在React中获取数据后,如何避免不必要的组件闪现1秒?

如何在Angular中插入动态组件

React 17与React 18中的不同setState行为

如何从一个列表中创建一个2列的表?

PrivateRoute不是路由组件错误

在服务器上放置了Create Reaction App Build之后的空白页面

在拖放时阻止文件打开

在带有背景图像和圆形的div中添加长方体阴影时的重影线

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

如何将innerHTML字符串修剪为其中的特定元素?

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

如何在 Select 文本时停止Click事件?

如何使用Astro优化大图像?

如何组合Multer上传?

Cherrio JS返回父div的所有图像SRC

如何在每隔2分钟刷新OKTA令牌后停止页面刷新

为什么这个最小Angular 的Licial.dev设置不起作用?