简体   繁体   中英

Auto-populate fields in a form based on a select with data taken from spreadsheet

I have done a web app with GAS that send the data on submit to a spreadsheet A.
There is also a select option that take some data dynamically from another spreadsheet B ("xxx") in column A.

This is the code:

In Code.gs:

function address() {
  var sheet   =  SpreadsheetApp.openById("xxx").getSheetByName("Sheet3");
  var lastRow = sheet.getLastRow();
  var myRange = sheet.getRange("A1:A" + lastRow); 
  var data    = myRange.getValues();
  var optionsHTML = "";
  for (var i = 0; i < data.length; i+=1) {
    optionsHTML += '<option>' + data[i][0] + '</option>';
  };
  return optionsHTML;
}

In Index.html:

<select class="custom-select" name="test" id="test">
 <?!= address(); ?>
</select>

I would to auto-populate other to two fields in the form based on the Columns B e C corresponding to the value in Col A that is in the select option.

For example, if in the spreadsheet B ("xxx") in the select option I choose "Italy", there will be also two fields not editable by the user, with the data "Tom" and "Red" inside.

+-----------------------+---------+-------+
| Col A (Select Option) |  Col B  | Col C |
+-----------------------+---------+-------+
| Italy                 | Tom     | Red   |
| USA                   | Michael | Green |
| Africa                | Anna    | Blue  |
+-----------------------+---------+-------+

(Output)

输出:

How can I proceed?

Update 1 (I am trying with the solution of Tanaike)

Code.gs

function doGet(request) {
  return HtmlService.createTemplateFromFile('Index')
      .evaluate();
}

/* @Include JavaScript and CSS Files */
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

/* @Process Form */
function processForm(formObject) {
  var url = "xxxx";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Data");
  
  ws.appendRow([formObject.azienda,
                formObject.test,
                formObject.field1,
                formObject.field2]);
}

function address() {
  var sheet   =  SpreadsheetApp.openById("xxxx").getSheetByName("Sheet3");
  var lastRow = sheet.getLastRow();
  var myRange = sheet.getRange("A2:C" + lastRow);  // Modified
  var data    = myRange.getValues();
  var optionsHTML = "";
  for (var i = 0; i < data.length; i+=1) {
    optionsHTML += `<option data-values="${data[i][1]},${data[i][2]}">${data[i][0]}</option>`;  // Modified
  };
  return optionsHTML;
}

Index.html

<!DOCTYPE html>
<html>
    <head>
        <base target="_top">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-8">
                    <form id="myForm" onsubmit="handleFormSubmit(this)">
                        <p class="h4 mb-4 text-center">Contact Details</p>

                        <div class="form-row">
                            <div class="form-group col-md-12">
                                <label for="azienda">Azienda</label>
                                <input type="text" class="form-control" id="azienda" name="azienda" required="">
                            </div>
                            
                        <div class="form-group col-md-2">
                             <label for="test">Ateco 1</label>
                             <select class="custom-select" name="test" id="test">
                             <?!= address(); ?>
                             </select>
                        </div>
                        
                        <div class="form-group col-md-5">
                            <label for="field1">Field1</label>
                            <input type="text" class="form-control" id="field1" name="field1" disabled="disabled">
                        </div>
                        
                        <div class="form-group col-md-5">
                            <label for="field2">Field2</label>
                            <input type="text" class="form-control" id="field2" name="field2" disabled="disabled">
                        </div>
                        
                    </div>

                        <button type="submit" class="btn btn-primary btn-block">Inserisci in Master Leads</button>
                    </form>
                    <div id="output"></div>
                </div>
            </div>      
        </div>
    </body>
  <?!= include('JavaScript'); ?>
</html>

Javascript.html

<script>
  // Prevent forms from submitting.
  function preventFormSubmit() {
    var forms = document.querySelectorAll('form');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
      event.preventDefault();
      });
    }
  }
  window.addEventListener('load', preventFormSubmit);    
      
      
  function handleFormSubmit(formObject) {
    google.script.run.processForm(formObject);
    document.getElementById("myForm").reset();
  }
  
  function setValues(select) {
  const [v1, v2] = select.options[select.selectedIndex].dataset.values.split(",");
  document.getElementById("field1").value = v1;
  document.getElementById("field2").value = v2;
}

  const select = document.getElementById("test");
  setValues(select);
  select.addEventListener("change", () => setValues(select));

</script>

I believe your goal as follows.

  • When an option, which is the value of column "A", is selected, you want to set the values from the column "B" and "C" to the input tags with the readonly.

Modification points:

  • In this modification, when address() is run at <?;= address()? ?> <?;= address()? ?> , the values of columns "A" to "C" are set to the options. The values of columns "B" and "C" are set to the custom attribute. And in HTML side, 2 input tags are added as disabled="disabled" you expect.
  • When the other option is selected, the values of columns "B" and "C" are set to 2 input tags using Javascript.
  • In your sample values of Spreadsheet, it seems that the 1st row is header row.

When your script is modified, it becomes as follows.

Modified script:

Google Apps Script side: Code.gs

function address() {
  var sheet   =  SpreadsheetApp.openById("xxx").getSheetByName("Sheet3");
  var lastRow = sheet.getLastRow();
  var myRange = sheet.getRange("A2:C" + lastRow);  // Modified
  var data    = myRange.getValues();
  var optionsHTML = "";
  for (var i = 0; i < data.length; i+=1) {
    optionsHTML += `<option data-values="${data[i][1]},${data[i][2]}">${data[i][0]}</option>`;  // Modified
  };
  return optionsHTML;
}

HTML&Javascript side: index.html

In this modification, 2 input tags and Javascript were added.

<select class="custom-select" name="test" id="test">
  <?!= address(); ?>
</select>
<input type="text" id="field1" disabled="disabled">
<input type="text" id="field2" disabled="disabled">

<script>
function setValues(select) {
  const [v1, v2] = select.options[select.selectedIndex].dataset.values.split(",");
  document.getElementById("field1").value = v1;
  document.getElementById("field2").value = v2;
}

const select = document.getElementById("test");
setValues(select);
select.addEventListener("change", () => setValues(select));
</script>

Note:

  • Please use this Google Apps Script with enabling V8.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM