Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations

Emp No *
Punch *
Customer details / mode or travel

All the data collected is stored in a Google spreadsheet structured as follows:

Timestamp   Emp No  Punch   Remark  Name    GeoCode GeoAddress  Email

With a certain script, I am able to capture the GPS coordinates of the users. I created a web app where anyone, even without an account, can access it and click the link.

However, there are a few issues I am facing:

I wish to store the email ID (or employee number) of the user filling out the form. Unfortunately, the email ID does not get captured. It only works when I fill out the form myself. How can I capture this information for all users without requiring them to authenticate the script?

If the GPS information is missing (empty), I want to display a different message on the HTML page. Is there a way to do this?

Below is the relevant code:

function doGet() {
    return HtmlService.createHtmlOutputFromFile("Index");
}
//
function getLoc(value) {
  var destId = FormApp.getActiveForm().getDestinationId() ;
  var ss = SpreadsheetApp.openById(destId) ;
  var respSheet = ss.getSheetByName("Location");
  var numResponses = respSheet.getLastRow();
  var currentemail = Session.getActiveUser().getEmail();
  var c=value[0]; var d=value[1];
  var e=c + "," + d ;
  //respSheet.getRange(numResponses,6).setValue(e);
  //respSheet.getRange(numResponses,8).setValue(currentemail);
  var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
  var f= response.results[0].formatted_address;
  //respSheet.getRange(numResponses,7).setValue(f);
  respSheet.getRange(numResponses,6,1,3 ).setValues([[ e, f, currentemail ]]);
}
//

index.html

<!DOCTYPE html>
<html>
<script>
(function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
      }
})()      
function showPosition(position){
 var a= position.coords.latitude;
 var b= position.coords.longitude;
 var c=[a,b]
 getPos(c)
 function getPos(value){
 google.script.run.getLoc(value);
 }
}

</script>
<body>
<p>Please ensure your GPS is on to record your location. You can generate the report from website to check. Pl. close this window (version 3)</p>
</body>
</html>

Answer №1

After receiving a query

I am looking to store the email ID (or employee number) of the individual filling out the form. However, I am facing issues with capturing the email ID in the form submission process. Although it works when I fill out the form myself, it does not work for other users. I am seeking a method to capture this information without requiring all users to authenticate the script or be logged in. Is there an alternative approach that can achieve this?

If you are using a web application built with Google Apps Script to automatically retrieve user email IDs, you have the option to configure the application to run as the user executing it rather than yourself. However, if you prefer not to utilize this functionality, then you will need to implement your own authentication mechanism.

Regarding the inquiry raised

In cases where the GPS location is not captured and remains empty, I aim to display a distinct message on the HTML page. How can this be accomplished?

You can address this by employing a JavaScript conditional expression

function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      alert('Can\'t get the position');
    }
})() 

function showPosition(position){
 var a= position.coords.latitude;
 var b= position.coords.longitude;
 var c=[a,b];
 getPos(c);
 function getPos(value){
 google.script.run.getLoc(value);
 }
}

The provided code snippet uses alert, but utilizing the DOM is also an option.

Additional Resources

Answer №2

Successfully created a comprehensive solution using only HTML, without relying on Google Forms. Also implemented an alert message functionality. However, the "Login" feature is still non-functional.

Code.gs

This script executes a form and stores the responses in designated columns within a Google Sheet. It offers faster performance compared to Google Forms, requiring only one click on the "Submit" button. The use of "append row" prevents data jumbling between rows, eliminating previous issues with data consistency.


/* @Include JavaScript and CSS Files */
function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
  .getContent();
}

/* @Process Form */
function processForm(formObject) {
  var url = "https://docs.google.com/spreadsheets/d/...../edit#gid=52499297";
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Location");
  var response = Maps.newGeocoder().reverseGeocode(formObject.lat, formObject.long);
  var address= response.results[0].formatted_address;
  ws.appendRow(
    [
      new Date(),
      formObject.empno,
      formObject.punch,
      formObject.rem,
      "",
      formObject.lat+","+formObject.long,
      address
    ]
  );
}



Index.html

This file contains the survey questions.

<!DOCTYPE html>
<html>

<head>
    <base target="_top">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <?!= include('JavaScript'); ?>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-6">
                <form id="myForm" onsubmit="handleFormSubmit(this);">
                    <p class="h4 mb-4 text-left">Record Attendance and Location</p>

                    <div class="form-group">
                        <label for="empno">Emp No - <a href="https://docs.google.com/spreadsheets/d/1yhcUpfhvyPcWyDkwglJRJwMn7VnBYEHaAjz959JC0wk/edit#gid=0">Click to see list</a></label>
                        <input type="number" class="form-control" id="empno" name="empno"  min="1" max="9999999"  required>
                    </div>

                    <div class="form-group">
                        <label for="punch">Punch (Select one)</label>
                        <select class="form-control" id="punch" name="punch" required>
                            <option selected disabled hidden style='display: none' value=''></option>
                            <option value="In">In</option>
                            <option value="Out">Out</option>
                            <option value="Started">Started</option>
                            <option value="Reached">Reached</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="rem">Remark</label>
                        <input type="text" class="form-control" id="rem" name="rem">
                    </div>


                    <div class="form-group">
                        <input type="hidden" class="form-control" id="lat" name="lat">
                        <input type="hidden" class="form-control" id="long" name="long">
                    </div>

                    <button type="submit" class="btn btn-primary btn-block">Submit</button>
                </form>

                <div id="output"></div>
            </div>
        </div>
    </div>
</body>

</html>


JavaScript.html

This file handles the processing of user responses.

<script>
    function showPosition() {
        navigator.geolocation.getCurrentPosition(showMap);
    }

    function showMap(position) {
        // Get location data
        var lat = position.coords.latitude;
        var geo1 = document.getElementById("lat");
        geo1.value = lat;
        var long = position.coords.longitude;
        var geo2 = document.getElementById("long");
        geo2.value = long;
    }

    // Prevent forms from submitting.
    function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
            forms[i].addEventListener('submit', function(event) {
                event.preventDefault();
            });
        }
    }
    window.addEventListener('load', preventFormSubmit);
    window.addEventListener('load', showPosition);

    function handleFormSubmit(formObject) {
        google.script.run.processForm(formObject);
        document.getElementById("myForm").reset();
        alert('Data saved successfully');
        
    }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

What steps can be taken to ensure that the v-model input is not updated?

Typically, when a user enters a value in an input field, it automatically updates a model. However, I am looking to temporarily prevent this automatic update. In my application, I have a canvas where users can draw grids by entering lengths and widths in i ...

Ways to retrieve the checkbox value using PHP in conjunction with XML

I am currently in the process of learning PHP, XML, AJAX, and other related technologies. I have a form that is working fine for the most part, but I am facing an issue with passing the value/state of a checkbox to my PHP script. It's worth mentionin ...

I'm having trouble making a Javascript ajax request to my Web API controller page. It seems like I just can't figure out the correct URL

Currently, I am facing an issue with my registration page where I am attempting to save input fields into a new record in the Users table. <button class="btn-u" type="submit" onclick="submitclicked()">Register</button> The click event trigger ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

To properly render an HTML file before loading a JavaScript file, express.static fails to serve the HTML file

Within my server.js file, the following code is present: var path = require('path'); var express = require('express'); var app = express(); var htmlRoutes = require('./app/routing/routes.js')(app, path, express); As for my r ...

What are some tips for utilizing the "bottom-row" slot within the "b-table" component in bootstrap-vue?

I am working on a component that utilizes the bootstrap-vue b-table component. My goal is to create a bottom row that displays the sum of each column in the table. However, I encountered an issue where the bottom-row only fills the first column, leaving ...

Having trouble displaying dynamically added images in my jsx-react component. The images are not showing up as expected

import React from "react"; import ReactDOM from "react-dom"; var bImg = prompt("Enter the URL of the image you want to set as the background:"); const bStyle = { backgroundImage: "url(bImg)"; // The link is stored ...

Count Scroller - Finding a Solution for _.debounce

Issue with Counter I have a counter that should increase or decrease by one each time the user scrolls up or down. The problem I'm facing is that my counter $('html').on('mousewheel', function (e) { var delta = e.originalEve ...

Navigating with buttons in the Material UI Drawer

I have implemented a Material UI drawer with some modifications. The original code used buttons, but now I want to navigate to a new page when a button is clicked. For example, clicking on the 'INBOX' button should take me to a page '/new&ap ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

Extract the chosen document from an input within the Electron application form

Need help with this form <form> <input type="file" name="idp" id="idp" onchange="uploadFiles();"/> </form> Once a user selects an image, I want to move it to a specific folder and save its full name in a variable for database storage. ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

Can you merge multiple req.body requests?

I am exploring a scenario where I have a list of items that need to be iterated through, with each item having the value of i added to it to retrieve the next set of information. For example: By concatenating the string "req.body.item" + i + "Title", you ...

Is it possible to execute functions inline with conditional logic in react?

Is there a way to shorten the long conditions inside an inline if-else statement in React by putting a function inside it? I attempted to do this but encountered an error stating that "discount is not defined." function getDiscount(props) { const d ...

Ways to allocate space evenly between components of the same size in React Native

As a beginner in Javascript and React-native, I have been experimenting with the technology to assess its viability for potential use in my current workplace. However, I have encountered some challenges with the user interface. To enhance my understanding ...

Converting EDN data to a string and back in Clojure/ClojureScript

When working with JavaScript, one can convert a JavaScript data structure into a JSON string using the following code: JSON.stringify({somedata: { somesubdata: {}}}) Then, to parse it back into a JS data structure, you can use: var my_obj = JSON.parse(" ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...