Search code examples
htmlgoogle-apps-scriptgoogle-sheets

Retrieve data set from Google Sheets from User Input Unique ID


I am attempting to find an easy way to have students enter an ID number and then have it retrieve corresponding data from a google sheet and display their first name, last name, and group assignment. I've been searching for a sample code etc to make this happen but haven't found anythign that works.


Solution

  • Get data dialog:

    google apps script:

    function findme(obj) {
      const uid = obj.uid;
      const ss = SpreadsheetApp.getActive();
      const sh = ss.getSheetByName("Sheet0");
      const vs = sh.getRange(2,2,sh.getLastRow() - 1,sh.getLastColumn()-1).getValues();
      const us = sh.getRange(2,1,sh.getLastRow() - 1).getValues().flat();
      const idx = us.indexOf(uid);
      if(~idx) {
        //Logger.log(vs[idx]);
        return JSON.stringify(vs[idx]);
      } else {
        return JSON.stringify(["No such id"]);
      }
    }
    
    function launchUidDialog() {
      let ui = HtmlService.createHtmlOutputFromFile('ah2');
      SpreadsheetApp.getUi().showModelessDialog(ui,"UID Dialog");
    }
    

    html: filename: ah2.html

    <!DOCTYPE html>
    <html>
      <head>
        <script>
          console.log("script");
        </script>
        <style> input{margin:2px;}</style>
      </head>
      <body>
         <div id="showme"></div>
         <form>
          <input type="text" id="uidtxt" name="uid" placeholder="Enter UID"/><br><input type="button" value="Submit ID" onClick= "getData(this.parentNode);"/><br><input type="button" value="clear" onClick="clearText();" />
        </form>
        <script>
          function getData(obj) {
            //console.log('obj: %s',JSON.stringify(obj));
            google.script.run.withSuccessHandler((vs) => {
              //console.log('vs: %s',vs);
              let data = JSON.parse(vs);
              document.getElementById("showme").innerHTML = data.join(",")
            }).findme(obj)
          }
          function clearText() {
            document.getElementById("uidtxt").value='';
            document.getElementById("showme").innerHTML='';
          }  
        </script>  
      </body>
    </html>
    

    Sheet0 Data File

    A B C D
    1 uid first last grp
    2 uid1 first1 last1 grp1
    3 uid2 first2 last2 grp2
    4 uid3 first3 last3 grp3
    5 uid4 first4 last4 grp4
    6 uid5 first5 last5 grp5
    7 uid6 first6 last6 grp6
    8 uid7 first7 last7 grp7
    9 uid8 first8 last8 grp8
    10 uid9 first9 last9 grp9

    Demo:

    enter image description here