I cannot get input to work under google app script

≡放荡痞女 提交于 2020-03-05 02:56:13

问题


I'm writing a web app under google sheets and can't get an input field to work. What am I doing wrong? everything works but uname is always empty (not undefined).

edit: I'm adding the full code after simplifying it as much as I could. In the log I get "name" regardless of the input I type in.

In the file code.gs:

function doGet () {
      var participant = {};

      var templ = HtmlService.createTemplateFromFile('out');   
      return templ.evaluate();;


}


function formSubmit(name) {

      Logger.log("name " + name);


      }

In out.html

    <!DOCTYPE html>
<html>
  <head>
      <base target ="_top">    
  </head>
  <body dir="rtl"; background-color: #92a8d1;>


    <label> Name 1 </label> <input type="text" id="firstname"><br>
    <label> Name 2 </label> <input type="text" id="lastname"> <br><br>
    <button type="button" id="send">Send</button>


     <script>

    document.getElementById("send").addEventListener("click", getData());

    function getData(){ 
      var uname = document.getElementById("firstname").value;   
      google.script.run.formSubmit(uname);


    }

      </script>





  </body>
</html>

回答1:


  • You want to retrieve the value of <input type="text" id="firstname"> when the button is clicked.
    • In your current situation, when you see the log with the script editor, only name is retrieved. This is your current issue.
  • You want to know the reason of the issue.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

  • In your script, document.getElementById("send").addEventListener("click", getData()); is used. In this case, when the HTML is loaded, getData() is run by () of getData(). By this, uname becomes "" and "" is sent to formSubmit(uname), then, when you see the log, you see name. And also, in this case, even when the button is clicked, google.script.run.formSubmit(uname); cannot be run. I think that this is the reason of the issue of your script in your question.

In order to avoid this, please modify your script as follows.

Modified script:

From:
document.getElementById("send").addEventListener("click", getData());
To:
document.getElementById("send").addEventListener("click", getData);
  • By the above modification for your script, when sample is inputted to "Name 1" and click "Send" button, you can see name sample at the log with the script editor.

Reference:

  • addEventListener()

If I misunderstood your question and this was not the result you want, I apologize.




回答2:


Here's an example form that you can probably use to accomplish your needs. This form is used as a simple receipt collection system. You can actually take and upload images from a mobile device with it. I also has text and button input types and upload a form node.

Code.gs

var receiptImageFolderId='';
var SSID='';

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};
}

The Html:

<!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>

Here's what the dialog looks like:



来源:https://stackoverflow.com/questions/59548213/i-cannot-get-input-to-work-under-google-app-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!