Cannot Pass InputBox String value From HTML To Google Apps Script - javascript

I created a sidebar for a Google Document that takes in user input. I'd like to use the collected data to update some fields on my document, but for now, I am just trying to display the data collected on screen via an alert to test if my code is working. Unfortunately, I am stuck and not sure what I am doing wrong.
There are two problems I am running into, but due to my limited knowledge of app script and coding as a whole, I just can't seem to resolve my issue. The problems I am having are, 1) my eventListener may not be be firing and 2) I can't seem to access the data collected from the input boxes.
Could someone assist me with this problem? I've been searching through the forum for an answer for a few days now, but again, my knowledge is very limited so it's possible I've come across the answer a few times, but just don't understand it. The code I am using is below and a link to my document is here.
App Script Code:
function onOpen() {
// Add a custom menu to the document.
var ui = DocumentApp.getUi(); // Or SpreadsheetApp or SlidesApp or FormApp.
ui.createMenu('Menu')
.addItem('Sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
// Create HTML template from a file
var html = HtmlService.createHtmlOutputFromFile('userform')
.setTitle("TEST FORM")
.setWidth(300);
DocumentApp.getUi()
.showSidebar(html);
}
function appendData(data) {
DocumentApp.getUi().alert(data.f + ' ' + data.l);
}
HTML code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div class="container">
<div>
<input id="firstName" type="text" name="firstName" placeholder="Enter first name">
</div>
<div>
<input id="lastName" type="text" name="lastName" placeholder="Enter last name">
</div>
<div>
<input type="button" value="SUBMIT" onClick="submitData();"/>
</div>
</div> <!-- End of container div -->
<script>
function submitData() {
var fName = document.getElementById('firstName').value;
var lName = document.getElementById('lastName').value;
var data {
f: fName,
l: lName
};
google.script.run.appendData(data);
}
</script>
</body>
</html>

Try this:
function submitData() {
var first=document.getElementById('firstname').value;
var last=document.getElementById('lastname').value;
var data={f:first,l:last};
google.script.run.appendData(data);
}
for simplicity you could also change this <button id="btn">Submit</button>
to this <input type="button" value="Submit" onClick="submitData();" />

Related

How would I go about creating this jump page?

Note: I'm a total novice at any coding. I'm just a dumb amature graphic designer. I've only ever created a page that lets me copy the
the most common phrases I had to leave in notes all day. I struggled
with it.
I'm trying to create this page that lets input something into a text field, and it applies it to defined URLS attached to buttons, that will bring me to those pages. Since I struggle to describe it, please see this visual: https://i.stack.imgur.com/ZplRK.jpg
I've tried co-opting some scripts for similar problems, but with no luck. (See below for examples before I edited them ). I included them to see if I was on the right track whatsoever. I know I'm gonna have an issue with multiple functions, probably?
<script type="javascript">
function goToPage(var url = '')
{
var initial = "http://example.com";
var extension = "html";
window.location(initial+url+extension);
}
</script>
<form name="something" action="#">
Label <input type="text" name="url" value="" onchange="goToPage(this.value)">
</form>
<SCRIPT type="javascript">
function goToPage(var url = '')
{
var initial = "https://cms.example.com/client/viewcasedetails";
var extension = "";
window.location(initial+url+extension);
}
</SCRIPT>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" name="url" value="" onSubmit="goToPage(this.value)">
<INPUT type="submit" value="GO">
That's where I at. I'm just tired of typing the same long URLs all day at work, and messing up more than half the time. I have no clue what the solution is - Javascript? HTML? CSS? Just trying to seek the DIY answer before looking on how to hire someone to make it. Which I have no clue how to do either but that's another question for later.
Thanks for helping / apologies for possibly super dumb questions.
You could do something like the following:
// grab the input element
const input = document.getElementById("cmsId");
// grab all links that need to be updated accordingly
// when value inside input element changes
const links = document.querySelectorAll("a");
// create a handler that listens for changes when
// you type some text into the input element
input.addEventListener("input", (event) => {
// grab value inside input elemenet
const value = event.target.value;
// iterate through all links and update
// the inner text + href attribute accordingly
// NOTE: `baseUrl` for each link is stored in a
// `data-*` attribute
links.forEach((link) => {
const baseUrl = link.dataset.url;
const url = baseUrl + value;
link.innerText = url;
link.href = url;
});
});
<!-- Use a simple input element here, no need for a form -->
<div>CMS ID: <input id="cmsId" type="text" /></div>
<div>
<!-- No need to create buttons, simple anchor elements will work just fine -->
<a
id="main"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewclientdetails/"
>
https://cmss.company.com/client/viewclientdetails/
</a>
</div>
<div>
<a
id="notes"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewnotes/"
>
https://cmss.company.com/client/viewnotes/
</a>
</div>
<div>
<a
id="docs"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/documentsall/"
>
https://cmss.company.com/client/documentsall/
</a>
</div>
<div>
<a
id="activity"
href="#"
target="_blank"
data-url="https://cmss.company.com/client/viewactivityledger/"
>
https://cmss.company.com/client/viewactivityledger/
</a>
</div>
In your code you are working with only the "main" button as I can see (as it goes to viewclientdetails). You are missing a "/" sign after var initial. So, assuming that you can implement the same functionality of the main button to the other buttons, here's what you can do:
<script type="text/javascript">
function goToPage(var url = '')
{
var initial = "https://cms.example.com/client/viewcasedetails/"; //I added the slash
var extension = "";
window.location(initial+url+extension);
}
</script>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" name="url" value="" onSubmit="goToPage(this.value)">
<INPUT type="submit" value="GO"> //you need 4 buttons here
You cannot have an input type="submit" here, since you will need four buttons. Submit works like a form submission. Add four buttons, then for each button's onClick property add the desired redirect url. You will need to get the value for the input field using an ID tag.
An example of what I am trying to say is given below:
<script type="text/javascript">
function onMainButtonClicked()
{
var cmsid= document.getElementById("cmsID").value;
var initial = "https://cms.example.com/client/viewcasedetails/"; //I added the slash
var extension = "";
window.location(initial+cmsid+extension);
}
function onNotesButtonClicked()
{
...
}
function onDocsButtonClicked()
{
...
}
function onActivityButtonClicked()
{
...
}
</script>
<TITLE>Redirect 1</TITLE>
<BASE HREF="https://cms.example.com/client/viewcasedetails">
</HEAD>
<BODY>
<P>
<FORM name="jump" action="#">
CMS ID:
<INPUT type="text" id="cmsID" name="url" value="">
<button onclick="onMainButtonClicked()">Main</button>
<button onclick="onNotesButtonClicked()">Notes</button>
<button onclick="onDocsButtonClicked()">Docs</button>
<button onclick="onActivityButtonClicked()">Activity</button>
There are much better ways to implement this, but this is a very simple implementation.

Javascript: parse parameters from URL then erase them in URL

I am trying to prefill some fields which are passed from URL as parameter pair. Having
www.example.com.com/myForm#myinput=123
as href send to end users, I am going to prefill the form field "myinput" with "123" after opening the link. However, the users will also see www.example.com.com/myForm#myInput=123 in their browser.
That's why I want to erase "myInput=123" from their URL. The reason for doing that is I don't want my users to see or even change the values in URL while filling the form.
I've tried
history.pushState(null, '', '/modifedURL')
either in HTML body "onload" or jquery "doc ready". As far I tried so far, this works only standalone without any parameter in URL like "www.example.com.com/myForm", but not with the additional injected parameters.
Here is simplified version of code what I got so far. Notice that the modifyURL Method is called successfully, but takes no effect on URL:
<head>
<meta charset="utf-8" />
</head>
<body onload="prefill();">
Your Body Content
<!-- Scripts at the bottom for improved performance. -->
<!-- jQuery, required for all responsive plugins. -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="myForm" method="POST">
<input id="myinput" maxlength="50" name="myinput" type="text" />
<br>
<input type="submit" name="submit" />
</form>
<script>
$(document).ready(function() {
//do some code after html is loaded
});
/*
window.onload = function () {
}
*/
function prefill() {
try{
var currentURL = window.location.href;
var n = currentURL.search("#");
var sPageURL = currentURL.substring(n+1);
var urlVal = getURLVal(sPageURL);
document.forms["myForm"]["myInput"].value = urlVal;
//change URL is called, but cannot change the URL!
modifyURL();
} catch(e){
alert("error " + e);
return false;
}
return true;
}
function modifyURL() {
history.pushState(null, '', '/modifedURL');
//even alert will fire, so pushState is skipped!!
alert('URL modified');
}
function getURLVal(query) {
//parse parameter pair in url
}
</script>
</body>
You can include the data diretly in your HTML, if it's meant to always be the same.
There are two ways:
1. <input id="myinput" maxlength="50" name="myinput" type="text" value="123" />
this actually puts the value inside your input field
2. <input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />
this only displays it before any real value is inserted by the user (on submit you don't get any value)
I hope this is useful for you

How do i add custom code from a user inside the <head> tag

i created a form builder, however, i need to find a way to have the person add their own tracking codes when they publish the forms, these tracking codes go in the code.
<section class="tracking-codes">
<h2> Please enter all tracking codes in here: </h2>
<form>
<input type="text" id="code" placeholder="Facebook Pixel"> </input>
<button type="button" onclick="codes()"> Add Code </button
</form>
</section>
here is my js
function codes ()
{
var trackingCode = document.getElementById('code');
document.head.appendChild(trackingCode);
console.log(trackingCode);
}
at this point, it does append the id of code but only the part of
<input type="text" id="code" placeholder="Facebook Pixel">
and not the user input, how would i go about doing this?
I have also tried the .value at the end of making the var of trackingcodes but it doesnt work.
Instead of adding html to the head section, you should use a hidden field input. Add it like this:
function codes ()
{
var trackingCode = document.getElementById('code').value;
var element = document.createElement('input');
element.type = 'hidden';
element.id = 'tracking';
document.head.appendChild(element);
console.log(trackingCode);
}

How to change content of page from input "forever"? (create primitive blog)

var text = document.getElementById('text');
var previousText;
function send() {
previousText = document.getElementById('text-place').innerHTML;
document.getElementById('text-place').innerHTML = text.value + "<br><br>" + previousText;
document.getElementById('text').value = "";
}
<!DOCTYPE html>
<html>
<body>
<input type="text" name="enter" class="enter" placeholder="Your text..." value="" id="text" />
<button onclick="send();" id="button">Send</button>
<p id="text-place"></p>
</body>
</html>
Hello, I need your help about one thing. I would like to create a primitive blog, but I can not figure out how to take value from the input of a "forever" be written to the tag so see it anyone, who comes to the site. I tried to search and I found only cookies in PHP. I have this JavaScript code, but I find out, that it's impossible. Does anyone here how to do it?Thanks in advance.

How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>

Categories

Resources