捕获来自Google Aps脚本中文本输入字段的输入 [英] Capturing input from a text input field in Google Aps script

查看:76
本文介绍了捕获来自Google Aps脚本中文本输入字段的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作表,其中包含有关我们使用的各种不同设备的信息.

I have a spreadsheet at work that contains information on various different devices we use.

电子表格包含原始设备制造商,存储容量,格式等信息,共有10列,当前最多359行;但是电子表格会从常规用途扩展.

The spreadsheet contains information like the Original Equipment Manufacturer, Storage capacity, format, Etc. There are a total of 10 Columns, and up to 359 rows currently; but the spreadsheet will expand from general use.

我已经使用Aps脚本和HTML在Google表格中创建了侧边栏应用程序,以简化对这些对象的请求支持.我遇到了捕获输入字段中输入的数据的问题.这是我的HTML:

I have created a sidebar application in google sheets using Aps script and HTML, in order to make requesting support for these objects simpler. I am running in to an issue with capturing the data typed into an input field. Here is my HTML:

<!DOCTYPE html>
<html>
  <head>
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  </head>

  <body>
  <div class = "Container"><!-- Begin CONTAINER div -->
    <div class="row"><!-- Begin ROW div -->
      <div class="col s24 "><!-- Beginning of Header div -->
        <h5 class="col s24"offset-s3> Edit a Kit </h5> 
        <div><!-- Text input field for Kit search -->
          <div class="input-field col s12">
            <textarea id="textarea1" class="materialize-textarea"></textarea>
            <label for="textarea1">Enter Kit Name</label>
          </div>
        </div><!-- end of Text Input for Kit search --> 

        <!-- Start of Submit btn div -->
          <div class="input-field col s12">
            <button class="btn waves-effect waves-light" id="search" onclick ="submitData()">Search
              <i class="material-icons right">search</i>
            </button> 
        </div><!-- End of Submit btn div -->

        <div class="divider"></div>

        <div><!-- beginning of kit contents div -->
        <!-- Users need to enter kit names into a text input field, similar to the create kit page -->
         <h5 id = "kit" class = "section"></h5>
        </div><!-- end of kit contents div -->

        <div class="divider"></div>
        <!-- Start of the HOME PAGE button Div -->
        <div class="input-field col s12">
          <button class="btn waves-effect waves-light" onclick="google.script.run.withSuccessHandler(changePage).newPage('Card Request Form')">Home
            <i class="material-icons right">home</i>
          </button>
        </div><!-- end of the HOME PAGE button div -->
      </div><!-- End of Header div --->
    </div><!-- End of ROW Div -->
  </div><!-- End of CONTAINER Div -->


  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

  <script>
  function changePage(page) {
    document.write(page);
  }

//  function alertA() {
//    alert("Your code Failed to Run");
//  };


  function alertB() {
    alert("Success! Click 'OK' to see your results");
  };


  function submitData() {
    var data = document.getElementById('search').value;
    var outPut = document.getElementById('kit');
    var display = outPut.innerHtml = "THIS IS WORKING AS EXPECTED";
//    alert(display);
  };

  function outputCard(submitData) {

  };

  </script>
  </body>
</html>

我正在尝试使用函数"submitData()"从"Submit btn div"访问输入数据,但是这样做没有成功.在我上传的版本中,我只是试图捕获该信息,然后将其打印回套件内容div",但未成功.

I am trying to access the input data from the "Submit btn div" using the function "submitData()", but have been unsuccessful in doing so. In the version i've uploaded, I am simply trying to capture that information, and print it back out to the "kit contents div" but have been unsuccessful.

为清楚起见,我在Google Apps脚本中执行此操作,作为Google表格电子表格的侧边栏扩展名.目的是接受该输入,并分析完整第一段中引用的所有信息的信息;然后在套件内容div"中返回与用户搜索字词相关的所有项目.但是,我无法捕获Google Apps脚本中的输入.这是我的gs代码的副本:

For clarity, I am doing this in a Google Apps scripts, as a sidebar extension to a google sheets spreadsheet. The goal is to take that input, and parse over the information for all of the informaton referenced in the first Full paragraph; and then return any items relevantr to the users search terms in the "kit contents div". I am not able to capture the input in Google Apps script though. Here is a copy of my gs code:

//This function searches for cards by the value typed into the text input field
function cardSearch(data) {
  var app = SpreadsheetApp;
  var log = app.openById("My Spreadsheet's ID");
  var kitContents = app.openById("My Spreadsheet's ID");
  var cards = log.getRange("A3:J").getValues();
  var kitType = kitContents.getRange("A3:J359").getValues();

for (i=0; i<kitType[data]; i++){
  return kitType[data];
  }

  Logger.log(kitType[356])
  // for some reason, the array literal ends at index #356, where as the spreadsheet is up to 359 rows, but stops at ID#354
};


function alert(data) {
  return "received input " +data.display;
};

//This function loads the webpage content of the HTML file "Card Request Form" as a sidebar in the main spreadsheet
function showRequestForm() {
  var form = HtmlService.createTemplateFromFile("Card Request Form");
  var html = form.evaluate();

  SpreadsheetApp.getUi().showSidebar(html);
};


//This function allows us to navigate pages that exists in the document
function newPage(page) {
  return HtmlService.createHtmlOutputFromFile(page).getContent()
};

我需要帮助了解如何对输入进行cpature,然后将其传递回GS(我认为这与将其传递给服务器相同),以便使用捕获的数据运行cardSearch函数.

I need help understanding how to cpature the input, and pass it back to the GS (I believe it's the same as passing it to the server) in order to run the cardSearch Function with that capturted data.

推荐答案

以下是我用来收集收据信息的示例表格.您可以将其显示为侧边栏,对话框,也可以将其作为webapp运行.它具有数字输入,文本输入和文本区域.它还允许您上传文件.

Here's an example form that I've used to collect receipt information. You can display it as a sidebar, a dialog or run it as a webapp. It has a numerical input, a text input and a textarea. It also allows you to upload a file.

thehtml.hmtl:

thehtml.hmtl:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
      $(function(){
        google.script.run
        .withSuccessHandler(function(rObj){
          $('#dt').val(rObj.date);
        })
        .initForm();

      });
      function fileUploadJs(frmData) {
        var amt=$('#amt').val();
        var vndr=$('#vndr').val();
        var img=$('#img').val();
        if(!amt){
          window.alert('No amount provided');
          $('#amt').focus();
          return;
        }
        if(!vndr) {
          window.alert('No vendor provided');
          $('#vndr').focus();
          return;
        }
        if(!img) {
          window.alert('No image chosen');
          $('#img').focus();
        }
        document.getElementById('status').style.display ='inline';
        google.script.run
        .withSuccessHandler(function(hl){
          document.getElementById('status').innerHTML=hl;
        })
        .uploadTheForm(frmData)
      }
      console.log('My Code');
    </script>
    <style>
      input,textarea{margin:5px 5px 5px 0;}
    </style>
  </head>
   <body>
    <h3 id="main-heading">Receipt Information</h3>
    <div id="formDiv">
      <form id="myForm">
        <br /><input type="date" name="date" id="dt"/>
        <br /><input type="number" name="amount" placeholder="Amount" id="amt" />
        <br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
        <br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
        <br/>Receipt Image
        <br /><input type="file" name="receipt" id="img" />
        <br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
      </form>
    </div>
  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
  </div>  
</body>
</html>

Codge.gs:

function onOpen() {
  SpreadsheetApp.getUi().createMenu('Receipt Collection')
    .addItem('Run as Dialog', 'showAsDialog')
    .addItem('Run as Sidebar', 'showAsSidebar')
    .addToUi();
  var sh=SpreadsheetApp.getActive().getSheetByName("Sheet1");
  sh.getRange(sh.getLastRow()+1,1).activate();
}

function uploadTheForm(theForm) {
  var rObj={};
  rObj['vendor']=theForm.vendor;
  rObj['amount']=theForm.amount;
  rObj['date']=theForm.date;
  rObj['notes']=theForm.notes
  var fileBlob=theForm.receipt;
  var fldr = DriveApp.getFolderById(receiptImageFolderId);
  rObj['file']=fldr.createFile(fileBlob);
  rObj['filetype']=fileBlob.getContentType(); 
  Logger.log(JSON.stringify(rObj));
  var cObj=formatFileName(rObj);
  Logger.log(JSON.stringify(cObj));
  var ss=SpreadsheetApp.openById(SSID);
  ss.getSheetByName('Sheet1').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
  var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
  return html;
}

function formatFileName(rObj) {
  if(rObj) {
    Logger.log(JSON.stringify(rObj));
    var mA=rObj.date.split('-');
    var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
    rObj.file.setName(name);
  }else{
      throw('Invalid or No File in formatFileName() upload.gs');
  }
  return rObj;
}

function doGet() {
  var output=HtmlService.createHtmlOutputFromFile('receipts').setTitle('thehtml');
  return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}

function showAsDialog() {
  var ui=HtmlService.createHtmlOutputFromFile('thehtml');
  SpreadsheetApp.getUi().showModelessDialog(ui, 'Receipts')
}

function showAsSidebar() {
   var ui=HtmlService.createHtmlOutputFromFile('thehtml');
  SpreadsheetApp.getUi().showSidebar(ui);
}

function initForm() {
  var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd")
  return {date:datestring};
}

globals.gs:

globals.gs:

var receiptImageFolderId='upload file folder id';
var SSID='spreadsheet id';

我希望这个例子可以帮助您满足您的需求.

I hope this example will help you to fulfill your needs.

这篇关于捕获来自Google Aps脚本中文本输入字段的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆