简体   繁体   中英

Searching a spreadsheet using Google Apps Script returns no data

I want to search for data in a spreadsheet and display the result to an HTML web page.

My problem : NO result is displayed on the webpage.

My Strategy:

  1. The database is saved on Google Drive as spreadsheet.
  2. The webpage visitor input a string in a text box and click search button.
  3. Searching in Column A for the string and return the data of the same Row.
  4. Put the result data of the row in the webpage (same page) as table.
function doGet() {
 return HtmlService.createTemplateFromFile('index').evaluate();
  var searchString = document.getElementById('searchString').value;
} 

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menuEntries = [ {name: "Search", functionName: "onSearch"} ];
  ss.addMenu("Commands", menuEntries);    
}

function onSearch() {
    var searchString = function doGet() {
                       document.getElementById('searchString').value;
                       }
    var sheetActive = SpreadsheetApp.openById("1MQVrQ7fmkitP-KNvv9m17Yi0ykGWgF5UjrVh5yCP8RE");
    var sheet = sheetActive.getSheetByName("Sheet1");

    var column =1; //column Index   
    var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row
    var searchResult = columnValues.findIndex(searchString); //Row Index - 2

    if(searchResult != -1)
    {
        //searchResult + 2 is row index.
        SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 1));
         document.getElementById("searchResult").innerHTML = searchResult;

    }
 }

Array.prototype.findIndex = function(search){
  if(search == "") return false;
  for (var i=0; i<this.length; i++)
    if (this[i] == search) return i;

  return -1;
}
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>

<body>
<input type="text" id="searchString" name="searchString" />

    <script>
      google.script.run.doGet();
      google.script.run.onOpen();
    </script>

<a href="javascript: onSearch();">Search</a>
<div id="searchResult"></div>
</body>
</html>

I assume that it sa typo issue : You added a string : document.getElementById("searchResult").innerHTML = "searchResult";

and may have to remplace it with your variable :

document.getElementById("searchResult").innerHTML = searchResult;

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