最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - To store user's input from HTML pages during navigation from one page to another in Google Web Application

programmeradmin2浏览0评论

I try to made a google web application with multipage where user has to tick or untick on checkboxes based on applicable. I need to save those checkboxes status on HTML page using local storage during page navigation. If he navigate between pages then can see his selection. But unable to store and retrieve the data. As i am learning apps script so please guide me. Also if i return back to my first page then also can load my filled checkbox. In my case localStorage.getItem() always return false even after the checkbox is on ticked condition.

HTML First Page with JavaScript

    <!DOCTYPE html>
<html>
  <head>
    <style>
    .container {
      design: flex;
      flex-direction: column;
      justify-items: center;
      font-size: 30px;
    }
    </style>
    <base target="_top">
  </head>
  <body>
    <h1>1st Page of sheet</h1>

    <div class="container">
      <div>
        <label>Cricket</label>
        <input id="cb1" type="checkbox">
      </div>
      <div>
        <label>Football</label>
        <input id="cb2" type="checkbox">
      </div>
    </div>
      <a style="font-size:24px" href="<?= ScriptApp.getService().getUrl() ?>?view=trial">Next page</a>
    

    <script>
      let cricketCheckbox = document.getElementById("cb1");
      let footballCheckbox = document.getElementById("cb2");

      cricketCheckbox.addEventListener('change', function () {

        localStorage.setItem("checkbox1",cricketCheckbox.checked);
    
      });

      footballCheckbox.addEventListener('change', e => {

        if(e.target.checked){
          localStorage.setItem("checkbox2",footballCheckbox.checked);
        }
      });
    </script>

  </body>
</html>

HTML Second Page with JavaScript

<!DOCTYPE html>
<html>
  <head>
    <style>
    .container {
      design: flex;
      justify-items: center;
      font-size: 30px;
    }
    </style>
    <base target="_top">
  </head>
  <body>
    <h1>2nd Page of sheet</h1>
    <div class="container">

      <div>
        <label>Mobile Required</label>
      </div>
      <div>
        <input id="cb3" type="checkbox">
      </div>
      <div>
        <input type="button" id="btn1" value="Save">     
      </div>
      <div>
        <a href="<?= ScriptApp.getService().getUrl() ?>" >First Page</a> 
      </div>

    </div>

    <script>
      document.getElementById("btn1").addEventListener("click",eventFirst);

      function eventFirst() {
        let trial = {};
          trial.cbox1 = localStorage.getItem("checkbox1");
          trial.cbox2 = localStorage.getItem("checkbox2");
          trial.cbox3 = document.getElementById("cb3").checked;

        google.script.run.datasave(trial);
        alert("Data saved");
        localStorage.clear()
      }
    </script>
  </body>
</html>

Server side function (gs)

function doGet(e) {
  if(e.parameters.view == "trial") {
    return executeSecondPage();
  } else {
    return executeFirstPage();
  }
}

function executeFirstPage() {
  let htmlSheet = HtmlService.createTemplateFromFile("firstPage").evaluate();
  let htmloutput = HtmlService.createHtmlOutput(htmlSheet);
  return htmloutput;
}

function executeSecondPage() {
  let htmlSheet = HtmlService.createTemplateFromFile("secondPage").evaluate();
  let htmloutput = HtmlService.createHtmlOutput(htmlSheet);
  return htmloutput;
}
function datasave(trial) {
  sheet.appendRow([trial.cbox1,trial.cbox2,trial.cbox3,new Date])
}

I try to made a google web application with multipage where user has to tick or untick on checkboxes based on applicable. I need to save those checkboxes status on HTML page using local storage during page navigation. If he navigate between pages then can see his selection. But unable to store and retrieve the data. As i am learning apps script so please guide me. Also if i return back to my first page then also can load my filled checkbox. In my case localStorage.getItem() always return false even after the checkbox is on ticked condition.

HTML First Page with JavaScript

    <!DOCTYPE html>
<html>
  <head>
    <style>
    .container {
      design: flex;
      flex-direction: column;
      justify-items: center;
      font-size: 30px;
    }
    </style>
    <base target="_top">
  </head>
  <body>
    <h1>1st Page of sheet</h1>

    <div class="container">
      <div>
        <label>Cricket</label>
        <input id="cb1" type="checkbox">
      </div>
      <div>
        <label>Football</label>
        <input id="cb2" type="checkbox">
      </div>
    </div>
      <a style="font-size:24px" href="<?= ScriptApp.getService().getUrl() ?>?view=trial">Next page</a>
    

    <script>
      let cricketCheckbox = document.getElementById("cb1");
      let footballCheckbox = document.getElementById("cb2");

      cricketCheckbox.addEventListener('change', function () {

        localStorage.setItem("checkbox1",cricketCheckbox.checked);
    
      });

      footballCheckbox.addEventListener('change', e => {

        if(e.target.checked){
          localStorage.setItem("checkbox2",footballCheckbox.checked);
        }
      });
    </script>

  </body>
</html>

HTML Second Page with JavaScript

<!DOCTYPE html>
<html>
  <head>
    <style>
    .container {
      design: flex;
      justify-items: center;
      font-size: 30px;
    }
    </style>
    <base target="_top">
  </head>
  <body>
    <h1>2nd Page of sheet</h1>
    <div class="container">

      <div>
        <label>Mobile Required</label>
      </div>
      <div>
        <input id="cb3" type="checkbox">
      </div>
      <div>
        <input type="button" id="btn1" value="Save">     
      </div>
      <div>
        <a href="<?= ScriptApp.getService().getUrl() ?>" >First Page</a> 
      </div>

    </div>

    <script>
      document.getElementById("btn1").addEventListener("click",eventFirst);

      function eventFirst() {
        let trial = {};
          trial.cbox1 = localStorage.getItem("checkbox1");
          trial.cbox2 = localStorage.getItem("checkbox2");
          trial.cbox3 = document.getElementById("cb3").checked;

        google.script.run.datasave(trial);
        alert("Data saved");
        localStorage.clear()
      }
    </script>
  </body>
</html>

Server side function (gs)

function doGet(e) {
  if(e.parameters.view == "trial") {
    return executeSecondPage();
  } else {
    return executeFirstPage();
  }
}

function executeFirstPage() {
  let htmlSheet = HtmlService.createTemplateFromFile("firstPage").evaluate();
  let htmloutput = HtmlService.createHtmlOutput(htmlSheet);
  return htmloutput;
}

function executeSecondPage() {
  let htmlSheet = HtmlService.createTemplateFromFile("secondPage").evaluate();
  let htmloutput = HtmlService.createHtmlOutput(htmlSheet);
  return htmloutput;
}
function datasave(trial) {
  sheet.appendRow([trial.cbox1,trial.cbox2,trial.cbox3,new Date])
}
Share Improve this question edited Mar 19 at 11:09 Mister Jojo 22.6k6 gold badges25 silver badges44 bronze badges asked Mar 17 at 15:39 Sunil PandaSunil Panda 671 silver badge9 bronze badges 29
  • 2 What exactly do you mean when you say "unable to store..."? Is there a javascript error? Does it save or retrieve incorrectly? How/when/where are you calling this javascript? As it is, it appears that you are calling it on page load, not necessarily after they have checked any boxes or upon navigation. In other words, we need more context. – mykaf Commented Mar 17 at 15:42
  • 1 The setItem calls are setting strings (like "cricketCheckbox"), not the checked state of the elements. – danh Commented Mar 17 at 15:59
  • 2 There are missing < in the first opening label tag for both HTML pages. Besides fixing this, please add a minimal reproducible example. This should include the doGet function and the minimal complete HTML for each page. – Wicket Commented Mar 17 at 16:05
  • 3 Remove the quotes: localStorage.setItem("checkbox2",footballCheckbox). Provide minimal reproducible example. To be clear, minimal is just 1 part, it needs to be reproducible. – TheMaster Commented Mar 17 at 16:06
  • 1 But 'localStorage.getItem' return only false even after the checkbox is in checked condition. See the first comment in this answer: As it is, it appears that you are calling it on page load, not necessarily after they have checked any boxes or upon navigation You need to watch for the change event, addEventListener and then store the state to local storage, whenever there is a change to the checkbox. – TheMaster Commented Mar 18 at 1:17
 |  Show 24 more comments

1 Answer 1

Reset to default 2

Your web app requires two moments

  1. Open/load page. Navigating to another page, in this case, is the same.
  2. Check/Uncheck checkboxes.

When the user opens/loads a page, using or not a parameter in the web app URL, the web app should read the values from the local storage. Add the script tag below the checkboxes and localStorage.getItem(name, value).

When the user checks / unchecks any checkbox, the web app should save the checkbox state to local storage. Use an event listener to execute localStorage.setItem(name).

Please bear in mind that the checked property for checkboxes returns a boolean, but localStorage stores string values, so when getting the stored value, it should be converted to a boolean before updating the checkbox value.

Below is a minimal example of how this can be achieved. It uses the document.querySelectorAll(selector) to retrieve all the checkboxes and the element ID as the name of the localStorage item. It uses JSON.parse to convert the "false" and "true" to false and true respectively.

Server Side code (.gs file)

function doGet(e) {
  const pageNumber = e.parameter.page ?? 1;
  return HtmlService.createTemplateFromFile(`page${pageNumber}`).evaluate();
}

page1.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <fieldset>
      <input type="checkbox" id="football"><label>Football</label>
      <input type="checkbox" id="cricket"><label>Cricket</label>
      <input type="checkbox" id="fencing"><label>Fencing</label>
      <input type="checkbox" id="archery"><label>Archery</label>
      <input type="checkbox" id="rugby"><label>Rugby</label>
      <input type="checkbox" id="polo"><label>Polo</label>
    </fieldset>
    <a href="<?= ScriptApp.getService().getUrl() + '?page=2' ?>">Page 2</a>
    <script>
      document.querySelectorAll('input[type=checkbox]').forEach(checkbox => {
        checkbox.checked = JSON.parse(localStorage.getItem(checkbox.id));
        checkbox.addEventListener('change', checkHandler);  
      });

      function checkHandler(e){
        localStorage.setItem(e.target.id, e.target.checked);
      }
    </script>
  </body>
</html>

page2.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <fieldset>
      <input type="checkbox" id="baseball"><label>Baseball</label>  
      <input type="checkbox" id="basketball"><label>Basketball</label>  
    </fieldset>
    <a href="<?= ScriptApp.getService().getUrl()?>">Page 1</a>
    <script>
      document.querySelectorAll('input[type=checkbox]').forEach(checkbox => {
        checkbox.checked = JSON.parse(localStorage.getItem(checkbox.id));
        checkbox.addEventListener('change', checkHandler);  
      });

      function checkHandler(e){
        localStorage.setItem(e.target.id, e.target.checked);
      }
    </script>
  </body>
</html>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论