Skip to content Skip to sidebar Skip to footer

Google Apps Script: Html - Form Submit, Get Input Values

I'm trying to use a sidebar with a form to get user input. The code is bound to a Google Sheets file. Code.gs: function onOpen() { SpreadsheetApp.getUi() .createMenu('Custo

Solution 1:

Html form has a default behavior of navigating to the submission link. To prevent that default behavior you can use event.preventDefault() function in HTML like so:

 <form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this)">

Note: You can find more detailed explanation here

The form elements are sent as an object in the argument to the processForm function, to view them you can use JSON.stringfy(). Learn more about objects here

Your processForm function would be modified like so:

function processForm(formObject) {
  var ui = SpreadsheetApp.getUi();
  ui.alert(JSON.stringify(formObject))
  // To access individual values, you would do the following
  var firstName = formObject.firstname 
  //based on name ="firstname" in <input type="text" name="firstname">
  // Similarly
  var lastName = formObject.lastname
  var gender = formObject.gender
  ui.alert (firstName+";"+lastName+";"+gender)
}

Solution 2:

I think for html form, the default submit method is GET, and the submitted form data will be visible in the page address field.

You can try changing the method to POST:

  <form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this) method="post"">

Refer to this link https://www.w3schools.com/html/html_forms.asp#method

Edit: I tried this and realised we still need to add event.preventDefault();


Post a Comment for "Google Apps Script: Html - Form Submit, Get Input Values"