Get HTML input into Google sheet in a specific format - javascript

The code snippet below is part of a larger script that collects user input from an HTML file and store these user input into my Google sheet. The type of input fields from the line
formObject.firmenp all the way to the line formObject.zielplanung in my HTML file is date and have each their own specific ID. I want to get these dates in format day/month/year into my sheet.
Any idea or recommendation how to achieve that?
Thank you so much in advance for your help :).
function getFormValues(formObject){
if(formObject.RecId && checkID(formObject.RecId)){
var values = [[formObject.RecId.toString(),
formObject.name,
formObject.unternehmen,
formObject.rufnummer,
formObject.email,
formObject.firmenp,
formObject.onboarding,
formObject.selbsttraining,
formObject.crmm,
formObject.tblock1,
formObject.fdtblock,
formObject.wochentraining,
formObject.zielplanung,
formObject.changestatus]];
}else{
var values = [[new Date().getTime().toString(),
formObject.name,
formObject.unternehmen,
formObject.rufnummer,
formObject.email,
formObject.firmenp,
formObject.onboarding,
formObject.selbsttraining,
formObject.crmm,
formObject.tblock1,
formObject.fdtblock,
formObject.wochentraining,
formObject.zielplanung,
formObject.changestatus]];
}
return values;
}

You can make a function like the below and convert all your data using it. Use this function on your script page.
//2021-11-05
var getDate = document.getElementById("date").value;
console.log("Inputted data: " + getDate);
function getNewDateFormat(value){
var dateValue = new Date(value);
var monthPart = dateValue.getMonth() + 1;
var dayPart = dateValue.getDate();
var yearPart = dateValue.getFullYear();
var newFormat = dayPart + "/" + monthPart + "/" + yearPart;
return newFormat
}
console.log("Expected data: " + getNewDateFormat(getDate));
//dummy input
<input type="text" id="date" value="2021-11-05" />

Related

Passing a date between two pages

Ok, so I have an MVC webapp. I've tried for hours to pass one simple variable from TransactionsDatePicker.cshtml to Transactions display.
I have an input with an id of 'transactionlookupdate'. I want to intercept it (input type is date).
I've managed to append the date to the link like this:
<script>
document.getElementById("buttoncontinue").addEventListener("click", function () {
dateSelected = document.getElementById("transactionlookupdate").value;
document.location.href = 'TransactionsDisplay' + '/' + dateSelected;
});
</script>
Now, what do I do in TransactionsDisplay (where I want to get the date) to store it in usable variable?!
So far I've tried like a 100 different ways, one that got me the closest was:
(top of TransactionsDisplay.cshtml)
#{
ViewBag.Title = "TransactionsDisplay";
Layout = "~/Views/Shared/_Layout.cshtml";
var dateSelected = Request.Url.Segments.Last();
}
and awful try at populating alert with dateSelected:
<script>
function myFunction() {
alert(dateSelected);
}
</script>
Any help would be appreciated!
Pass the date as url parameter in TransactionsDatePicker.cshtm
document.location.href = 'TransactionsDisplay' + '?date=' + dateSelected;
and extract in TransactionsDisplay at the end of the <body> element:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const myDate = urlParams.get('date');
alert(myDate); // test alert
</script>

How do I add a new value to a Google Sheet from a text field in a Web App and then automatically update the associated dropdown?

WARNING: I'm not a programmer by trade.
Ok. Got the disclaimer out of the way. So this might not be the best way to do this but here is the scenario. I have a dropdown that gets populated via a Google Sheet. The user chooses a selection from the list but this dropdown does not have all of the possible values it could have. There will likely be a time when the user needs a new value added. While I could manually update the spreadsheet as new values are requested that introduces an element of human availability to get this done and I'm not always available.
What I would prefer is a self-serve model. I want to supply the user with a text field where they can enter the new value and submit it to the Google Sheet. Then I would like the dropdown to be updated with the new value for the user to choose.
Now, I realize that I could just submit the value in the new field to the Google Sheet but that will require building a condition to see whether it is the dropdown or text field that has a value in it. I'd also need some type of error handling in case both the dropdown and text field have values. That seems like a bigger headache to program then my ask.
I'm not sure what code you would need to see to help make this work but here is what I think might help.
doGet function
function doGet(e){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("External");
var range = ws.getRange("A2:D2");
var valuesArray = [];
for (var i = 1; i <= range.getLastColumn(); i++){
var lastRowInColumn = range.getCell(1, i).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var list = ws.getRange(2,i,lastRowInColumn-1,1).getValues();
valuesArray.push(list);
}
var userEmail = Session.getActiveUser().getEmail();
var sourceListArray = valuesArray[2].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var productListArray = valuesArray[3].map(function(r){ return '<option>' + r[0] + '</option>'; }).join('');
var tmp = HtmlService.createTemplateFromFile("config");
tmp.productList = productListArray;
return tmp.evaluate();
}
Add to Google Sheet
function userClicked(tagInfo){
var ss = SpreadsheetApp.openById(ssId)
var ws = ss.getSheetByName("Data");
ws.appendRow([tagInfo.email, tagInfo.source, tagInfo.product, new Date()]);
}
Add record
function addRecord(){
var tagInfo = {};
tagInfo.product = document.getElementById("product").value;
google.script.run.userClicked(tagInfo);
var myApp = document.getElementById("source");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("brand");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
var myApp = document.getElementById("product");
myApp.selectedIndex = 0;
M.FormSelect.init(myApp);
}
How dropdowns are populated in the HTML.
<div class="input-field col s3">
<select id="product" onchange="buildURL()">
<option disabled selected value="">Choose a product</option>
<?!= productList; ?>
</select>
<label>Product</label>
</div>
Need to see anything else? I think it might be relatively easy to add the new value to the column but the tricky part seems to be the update of only that one dropdown and not the entire app. To me it seems like I want to trigger the doGet() function again but only for that specific dropdown. Thoughts?
UPDATE: current code to add new value to dropdown
function addProduct() {
let newProd = document.getElementById("newProduct").value;
google.script.run.withSuccessHandler(updateProductDropdown).addNewProduct(newProd);
document.getElementById("newProduct").value = "";
}
function updateProductDropdown(newProd){
var newOption = document.createElement('option');
newOption.value = newProd;
newOption.text = newProd;
document.getElementById('product').add(newOption);
}
UPDATE2: App Scripts function to add new value to column in spreadsheet
function addNewProduct(newProd){
var columnLetterToGet, columnNumberToGet, direction, lastRow, lastRowInThisColWithData, rng, rowToSet, startOfSearch, valuesToSet;
var ss = SpreadsheetApp.openById(ssId);
var ws = ss.getSheetByName("List Source - External");
lastRow = ws.getLastRow();
//Logger.log('lastRow: ' + lastRow)
columnNumberToGet = 9;//Edit this and enter the column number
columnLetterToGet = "I";//Edit this and enter the column letter to get
startOfSearch = columnLetterToGet + (lastRow).toString();//Edit and replace with column letter to get
//Logger.log('startOfSearch: ' + startOfSearch)
rng = ws.getRange(startOfSearch);
direction = rng.getNextDataCell(SpreadsheetApp.Direction.UP);//This starts
//the search at the bottom of the sheet and goes up until it finds the
//first cell with a value in it
//Logger.log('Last Cell: ' + direction.getA1Notation())
lastRowInThisColWithData = direction.getRow();
//Logger.log('lastRowInThisColWithData: ' + lastRowInThisColWithData)
rowToSet = lastRowInThisColWithData + 1;
valuesToSet = [newProd];
ws.getRange(rowToSet, 9).setValues([valuesToSet]);
return newProd;
}
SOLUTION to Update Materialize Dropdown
function updateProductDropdown(newProd){
newProdOption = document.getElementById('product');
newProdOption.innerHTML += '<option>' + newProd + '</option>';
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
}
You can specify a client side callback function if you use google.script.run withSuccessHandler(callback) where your callback could update the list only and not the whole site.
Example:
google.script.run.withSuccessHandler(updateDropdownWidget).updateDropdownList(text_from_input)
Where updateDrownList(text_from_input) is a function in your Apps Script that adds text to the sheet using SpreadsheetApp for example, and returns the "text" to the callback function: updateDropdownWidget(text) which adds a new list item to the HTML drop-down list in your front end.
index.html:
<form>
<label for="newOption">New option for the dropdown:</label>
<input type="text" id="nopt" name="newOption">
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(updateDropdownWidget)
.updateDropdownList(document.getElementById('nopt').value)">
</form>
<label for="cars">Choose a car:</label>
<select name="cars" id="cars">
<?!= values; ?>
</select>
<script>
function updateDropdownWidget(text){
var option = document.createElement('option');
option.value = text;
option.text = text;
document.getElementById('cars').add(option);
}
</script>
Code.gs:
function doGet(e){
var ss = SpreadsheetApp.getActiveSheet();
var lastRow = ss.getDataRange().getLastRow();
var values = ss.getRange(1,1,lastRow,1).getValues();
var valuesArray = [];
for (var i = 0; i < values.length; i++){
valuesArray.push('<option value="'+values[i]+'">' +values[i]+ '</option>');
}
var tmp = HtmlService.createTemplateFromFile("index");
tmp.values = valuesArray;
return tmp.evaluate();
}
function updateDropdownList(text_from_input){
// Log the user input to the console
console.log(text_from_input);
// Write it to the sheet below the rest of the options
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getDataRange().getLastRow();
sheet.getRange(lastRow+1,1).setValue(text_from_input);
// Return the value to the callback
return text_from_input;
}
Here's an example:
In my Stack Over Flow spreadsheet I four buttons which can be used to run any function in 3 script files and every time I load the sidebar it reads the functions in those script files and returns them to each of the select boxes next to each button so that I test functions that I write for SO with a single click and I can select any function for any button. Here's the Javascript:
$(function(){//JQuery readystate function
google.script.run
.withSuccessHandler(function(vA){
let idA=["func1","func2","func3","func4"];
idA.forEach(function(id){
updateSelect(vA,id);
});
})
.getProjectFunctionNames();
})
Here is GS:
function getProjectFunctionNames() {
const vfilesA=["ag1","ag2","ag3"];
const scriptId="script id";
const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content?fields=files(functionSet%2Cname)";
const options = {"method":"get","headers": {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}};
const res = UrlFetchApp.fetch(url, options);
let html=res.getContentText();
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Project Functions");
let data=JSON.parse(res.getContentText());
let funcList=[];
let files=data.files;
files.forEach(function(Obj){
if(vfilesA.indexOf(Obj.name)!=-1) {
if(Obj.functionSet.values) {
Obj.functionSet.values.forEach(function(fObj){
funcList.push(fObj.name);
});
}
}
});
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(funcList.join(', ')), "Project Functions");
return funcList;//returns to withSuccessHandler
}
Image:
Animation:

Display nested data from Firebase in html using javascript?

please help me with my code. I tried display retrieved data in my html table using javascript, but nothing work. I am new in firebase, if it possible please anyone help me or give advice, I have already tried everything methods on stack (
The structure of my base looks like this,please check the image from the link below
/Notes/{Generated User Token}/{Generated Date}/{Generated Note ID}/Fields
My Html Code
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Name:</th>
</table>
Javascript
var database = firebase.database();
var uid = firebase.auth().uid; // Not working, How to get a path to Generated tokens?
var date = // How to get a path to "DateddMMyyyy" from a structure?
var notes = // How to get a path to "NoteXXXXXXX" from a structure?
database.ref().child('Notes' +token+ '/' +date+ '/' +notes+ '/' ).once('value').then(function(snapshot) {
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.name + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
I do not know how to write a path to Generated Date "DateddMMyyyy" and Generated Note ID "NoteXXXXXXX"
I need only display end fields from structure. What should I edit in
my code?
Ps: For more details about Generated date, please check code from android studio "timeStamp = new SimpleDateFormat("ddMMyyyy").format(Calendar.getInstance().getTime());"
For getting the date formated id pass the input date to getDateId use it to construct the database.ref()
function getDateId(dt){
var date = new Date(dt);
var currentMonth = date.getMonth();
var currentDate = date.getDate();
if (currentMonth < 10) { currentMonth = '0' + currentMonth};
if (currentDate < 10) { currentMonth = '0' + currentDate};
return `Date${currentDate}${currentMonth}${date.getFullYear()}`
}
var inputDate = new Date();
var dateId = getDateId(inputDate);
console.log(dateId)

Pre-populate Form Field With The Internal Millisecond Clock From Javascript

I have a form on my website that I need to pre-populate with the current unix millisecond timestamp.
I do have another form field (in the same form) which successfully pre-populates the Date (Month, Day, Year) with the following code:
<div>DATE<br><input name="date" id="date"></div>
<script>
(function() {
var days = ['','','','','','',''];
var months =
['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ]; };
Date.prototype.getDayName = function() {
return days[ this.getDay() ]; }; })();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
document.getElementById('date').value = day + ' ' + month + ' ' +
now.getDate() + ', ' + now.getFullYear();
</script>
However... I'm not having the same luck when attempting to pre-populate a second form field with the Unix Millisecond timestamp using this code:
<div>TIMESTAMP URL<br><input name="timeStampURL" id="timeStampURL"></div>
<script>
var d = new Date();
document.getElementById('timeStampURL').innerHTML = d.getTime();
</script>
I don't understand why the two codes behave differently that way, but any advice as to how to get that script to pre-populate the field would be appreciated.
Input elements don't have any content, so setting their innerHTML property does nothing. Your first function is setting the value attribute, so should your second:
function showTimeValue() {
document.getElementById('timeValue').value = Date.now();
}
window.onload = showTimeValue;
<input id="timeValue">
<button onclick="showTimeValue()">Update time value</button>
Each time you run the code, you'll get an updated value.

Show string result from function in a label using AngularJs

What is the best way to call function that will return string and show that string in a label when using angularJs?
I have three drop downs, and when I select values in all of them I want to show a label.
Content of a label is calculated in one function so on that moment (when all 3 drop downs have some values selected) I need to call function that will return value for label as well.
All that hiding/showing label logic I have put in html like this:
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-value="convertSelectedTimeZoneToClients()"></div>
</div>
This is convertSelectedTimeZoneToClients() function code:
convertSelectedTimeZoneToClients() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
return localTime;
}
So when values are selected I am showing label that says: Your local time
And underneath I want to show result from convertSelectedTimeZoneToClients()that will be basically string in 'YYYY-MM-DD HH:mm' format.
Can I preform something like this on the html as well or I will have to move to controller? What is the best or easiest way to accomplish this?
I have tried ng-value, but I guess I am doing wrongly. Nothing gets show, but I do not get any errors in console as well.
in your function you can check if your drop downs are selected, then calculate and return result
$scope.getData = function () {
if ($scope.ValueOfFirstDropDown != undefined && $scope.ValueOfSecondDropDown != undefined && $scope.ValueOfThirdDropDown != undefined) {
//calculate result
return result;
}
}
and in your html
<label>{{getData()}}</label>
Try this:
<div ng-bind="convertSelectedTimeZoneToClients()"></div>
You should call this function on change of selected value
<select ng-change="convertSelectedTimeZoneToClients();"></select>
<div class="col-md-2"
ng-show="newTestSessionCtrl.formData.sessionTime && newTestSessionCtrl.formData.timeZone && newTestSessionCtrl.formData.sessionCloseInterval">
<lable>Your local time</lable>
<div ng-bind="clientDateTimeZone"></div>
</div>
and reflect $scope.clientDateTimeZone = yourreturnedvalue
No need to return any thing
$scope.convertSelectedTimeZoneToClients = function() {
let timeZoneInfo = {
usersTimeZone: this.$rootScope.mtz.tz.guess(),
utcOffset: this.formData.timeZone.offset,
selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime
};
let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
let localTime = this.$rootScope.mtz.utc(utcTime).toDate();
localTime = this.$rootScope.mtz(localTime).format("YYYY-MM-DD HH:mm");
//set It here
$scope.clientDateTimeZone = localTime
//return localTime;
}

Categories