How do I read input data in a form? - javascript

I'm just starting to learn JavaScript and therefore do not know much about how Forms are used or how to read from them. I'm trying to play around with Google's Geocode, and need some help with building a JS Form to read from.
I have the following JS code, outputting the longitude & latitude, and simply need a form to store some addresses in. The code I have looks as follows:
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value;
geocoder.geocode( {'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
results[0].geometry.location.latitude
results[0].geometry.location.longitude
}
else
{
alert("Geocode was not successful for the following reason: " + status)
}
});
I'd like some help if possible to build a form this code can read an address from, where the ElementID = "address". How would such a form look? I'd much appreciate if someone could take a minute or two and explain how the JS works with the form. Any help is appreciated! Thank you, guys.

JS dosent care what the element is you just need to get the reference of the form from the DOM then you can do what you want (get the value).
a simple form can look like this
<form>
First name:<br>
<input type="text" id="firstname"><br>
Address:<br>
<input type="text" id="address">
</form>
<button onclick="myFunc()">Done!</button>
So when the button is click it will run a function myFunc which will get your data from the form and alert it.
function myFunc(){
var name = document.getElementById("firstname").value;
var address = document.getElementById("address").value;
alert(name + " lives at " + address);
}
more on getting elements by id here
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
you can also use jquery
function myFunc(){
var name = $("#firstname").val();
var address = $("#address").val();
alert(name + " lives at " + address);
}
https://api.jquery.com/id-selector/

First create a Form in html. Include your external javascript file in it.
<head>
<script type="text/javascript" src="index.js"></script> //index.js is name of javascript file which is in same location of this jsp page.
</head>
<body>
<form name="EmployeeDetails" action="ServletEmployee" method="post">
Employee Name:<input type="text" id="name"><br>
EmployeeID:<input type="text" id="employID"><br>
<input type="submit" value="Submit">
</form>
<input type="button" name="Click" id="mybutton" onclick="myButtonClick">
</body>
In your external javascript file...that is index.js
window.onload = function(){ // function which reads the value from html form on load without any button click.
var employeename = document.getElementById("name").value;
var employeeid = document.getElementById("employID").value;
alert("Name : "+employeename+" : EmployeeID : "+employeeid);
}
function myButtonClick(){ // function to read value from html form on click of button.
var empname = document.getElementById("name").value;
var empid = document.getElementById("employID").value;
alert("Name : "+empname+" : EmployeeID : "+empid);
}

Related

Save the email ID of the user filling the form

I have a Google Form to collect information from my workers working in remote locations
Emp No *
Punch *
Customer details / mode or travel
The data goes into a Google spreadsheet with the below structure
Timestamp Emp No Punch Remark Name GeoCode GeoAddress Email
I am able to capture the GPS co-ordinates of the user by the below script. I made a web app (anyone even anonymous can run) and asked the user to click the link.
What I am not able to do :
I want to save the email ID (or emp no) of the user filling the form. But the email ID is not getting captured into the form. If I fill the form, the email ID is captured. For other users it is not captured. I don't want all the users to authenticate the script (to run the script as the logged in user). It must be captured by some other way. Is it possible?
If the GPS is not captured (it is empty), I want to display a different message in the HTML page. How to do it?
Code.gs
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>
From the question
I want to save the email ID (or emp no) of the user filling the form. But the email ID is not getting captured into the form. If I fill the form, the email ID is captured. For other users it is not captured. I don't want all the users to authenticate the script (to run the script as the logged in user). It must be captured by some other way. Is it possible?
On a web application created using Google Apps Script to automatically get the user email ID you could set your web application to be executed as the user running the application instead being executed as you but if don't want to use this feature then you have to set your own authentication process.
From the question
If the GPS is not captured (it is empty), I want to display a different message in the HTML page. How to do it?
Use 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 above code uses alert but you could use the DOM.
Resources
Web Apps | Google Apps Script
Document Object Model (DOM)
I was able to make a complete solution without any google form (just HTML) and managed to display an alert message also. The "Login" is still not possible.
Code.gs
It runs the form and saves the answers in the required columns into google sheet.
It runs faster than google form and "Submit" has to be clicked only once.
As the saving happens by "append row", the jumbling of data (between rows) which was happening in my earlier method is avoided.
/* #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 has the 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 - Click to see list</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 processes the answers
<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>

Populate email input on HTML form from email value within google sheets cell

I've created a pop-up email dialog box within google's html editor as follows with the input for email as follows:
<input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">
In my .gs file I'm storing the value of my cell containing the email address I want to use as follows:
function getEmail()
{
var s=SpreadsheetApp.getActive().getSheetByName("Template");
var row=15;
var column=3;
var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
Logger.log(contactAddress);
}
This works fine and is capturing the email address correctly and logging it. I now need to change the 'value' of my email input so that it populates with this address when the diolog opens. So I have the following in my HTML file:
window.onload = function (contactAddress)
{
document.getElementById('mail').value=contactAddress;
}
However, this is resulting in '[object Event]' being populated. I feel I'm close here but can't quite get it over the line!!!!
UPDATE:
So I added this to my .gs:
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('emailTemplate')
.setWidth(800)
.setHeight(500);
html.myvar = new getEmail();
html.evaluate().getContent();
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, ' ');
}
However, when I run the script I get an error stating Object does not allow properties to be added or changed.
Edit: Original answer deleted.
So here is my answer to your problem. Tested it out, and it works.
My HTML page is set up like this just to test it:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function onSuccess(contact) {
//var contactAddress = google.script.run.getEmail();
document.getElementById('mail').value=contact;
}
google.script.run.withSuccessHandler(onSuccess).getEmail();
</script>
</head>
<body>
<input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">
</body>
</html>
My .gs file contains
function getEmail()
{
var s=SpreadsheetApp.getActive().getSheetByName("Sheet1");
var row=1;
var column=3;
var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
Logger.log(contactAddress);
return contactAddress;
}
The only real difference is that I added a return statement (and changed the row from 15 to 1 for my test).
Seems the main problem was how you were calling the function on the HTML page. It needed a google.script.run.withSuccessHandler() call instead of a window.onload = function() call.

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.
What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).
HTML:
<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script>
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>
</head>
<body>
<form >
player one name: <input type="text" id="firstname"><br>
player two name: <input type="text" id="secondname"><br>
<input type="submit" onclick="checkNames();"/>
</form>
</body>
</html>
JavaScript:
function checkNames(){
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
//window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
//window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}
I have commented the two other options I tried which also do not work.
You are using an HTML form... this means that your submit button will fire and try to submit your form.
In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.
function checkNames() {
event.preventDefault();
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
window.location.href = 'SOME-PATH/Game.html';
}
To redirect to a page in your computer you can use:
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';
There are more than one way of passing the values to another page. Here is an example using query string.
In the page that has the values.
var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;
In the page receiving the values.
var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];
Use
window.location="url";

Minimal google geocoder not returning any result

Preface: I have contacted google and read the documentation. When this is finished it will display the map on the next page and have autosuggest on the first - I will not be violating the terms and conditions this way, so please dont start a flame war
I have set about trying to create my own minimal geocoder which geocodes without showing a map on the current page. I have found that there is no example code online for doing this! I am new to jquery but this is the best I could come up with. However, low and behold it doesn't work.
I am sure I have done something stupid, so I would appreciate it if someone could let me know if they spot any obvious reasons why this wouldn't work. I have never made a javascript before.
JSFiddle Link: http://jsfiddle.net/njDvn/9/
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
<input id="lat" type="textbox" value="lat">
<input id="lng" type="textbox" value="lng">
</div>
</body>
</html>
​
well first 2 things I can see are that the onclick of the button is calling codeAddress(), but you have not declared that function - you can change that to getLatLng() and it should work then. Plus the <body onload is calling initialize() which is also not declared. While that should not prevent the geocoder from firing you should probably fix it.

Why does the URL contain data from the HTML form?

On one of my pages in Drupal, I have a panel that contains the following html code:
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var dirService, initAddr, endLoc, doc;
function initialize() {
dirService = new google.maps.DirectionsService();
initAddr = "85 E San Fernando Street San Jose, CA 95113";
}
function showLocation() {
doc = document.getElementById("results_area");
endLoc = document.forms[0].address2.value;
findFromAddress();
}
function findFromAddress() {
dirService.route({'destination': initAddr, 'origin': endLoc, 'travelMode': google.maps.TravelMode.DRIVING}, function (result, status) {
if (status === google.maps.DirectionsStatus.OK) {
var distance = result.routes[0].legs[0].distance.value;
var miles = Math.round(distance * 0.000621371192 * 100) / 100;
alert("Distance from Loves Cupcakes is roughly" + miles
+ " miles" + "Estimated price is (price)" );
}
else {
alert("INVALID ZIP CODE");
}
});
}
</script>
</head>
<body onload="initialize()">
<p> Enter in zip code of desired delivery location</p>
<form action="#" onsubmit="showLocation(); return false;">
<p><input class="address_input" name="address2" size="20" type="text" /> <input name="find" type="submit" value="Search" /></p>
</form>
<p id="results_area"> </p>
Simply put, it takes a zipcode and calculates the distance from a specified location.
The HTML page works on its own, but when I enter it into a panel, some weird stuff happens that I don't understand. When I hit the "Submit" button, the page is reloaded, but with a slightly different URL and no alert box pops up. The URL changes from ../contact_us to ../Contact_Us?address2=&find=Search#. I understand the address2 and search are elements from my HTML code, but can anyone help me figure out why this is happening (I am assuming it has something to do with drupal, not the code itself, but not too sure)?
When the submit button is clicked, the browser sends a HTTP GET request to the address with the address2 and find values as parameters.
In your case, address2 has no value and find has a value of 'Search'
See here for a comprehensive explanation : https://www.rfc-editor.org/rfc/rfc3986#section-3

Categories

Resources