Why can't I get the search result using an app I made using Google App Script, even if I surely have the data?

Viewed 50

By following the instruction of this website, I made a web app using Google App Script (GAS) which will display the search when a user enters a search term (e.g. order number, status, price) in the search window and the search is successful (The screenshot below represents what I expected). However, my app always returns 'Data not found!' even if the search term exists in the data. What am I missing, then?

enter image description here

Components of the app

Data

A spreadsheet that contains the exactly same contents of the original spreadsheet (i.e. I copied the original contents and pasted them to my own spreadsheet to prepare the data)

Index.html

I copied the code from https://gist.github.com/bpwebs/dbbd96f8262e486c8f4c321ea0d3a95a#file-index-html and pasted it to 'Index.html' in my own GAS project.

Code.gs

I modified the original code on https://gist.github.com/bpwebs/dbbd96f8262e486c8f4c321ea0d3a95a#file-code-gs since the original code has an undefined variable (Sheets on ln.19) and cannot open the spreadsheet. I replaced the relevant code with SpreadsheetApp.openById() and range.getValues().

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate();
}
 
 
/* PROCESS FORM */
function processForm(formObject){  
  var result = "";
  if(formObject.searchtext){//Execute if form passes search text
      result = search(formObject.searchtext);
  }
  return result;
}
 
//SEARCH FOR MATCHED CONTENTS 
function search(searchtext){
  // var spreadsheetId   = '1p7fKVM7HA4Ikl8gYC2WesmHcIqAqJQWTfIuiqB4SyN4'; //** CHANGE !!!
  // var dataRage        = 'Data!A2:Y';                                    //** CHANGE !!!
  var ss = SpreadsheetApp.openById('The URL to my spreadsheet');
  var range = ss.getRange('Data!A2:Y');
  var data = range.getValues();
  // var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
  var ar = [];
   
  data.forEach(function(f) {
    if (~f.indexOf(searchtext)) {
      ar.push(f);
    }
  });
  return ar;
}
1 Answers

Sheets API is used in the original code:

(See: Enable the Google Sheets API advanced service)

Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;

By default, the values are formatted and are strings.

(See: ValueRenderOption)


indexOf performs exact match on each element and the passed value, where the data type has to be the same.

Your are now using https://developers.google.com/apps-script/reference/spreadsheet/range#getvalues that unformatted values are returned (number as number and date as date object), which would always return false when indexOf() (exact match) is performed.

To get formatted values (string), use getDisplayValues().

Related