I'm writing a web app under google sheets and can't get an input field to work. What am I doing wrong?
everything works but uname is always empty (not undefined).
edit: I'm adding the full code after simplifying it as much as I could.
In the log I get "name" regardless of the input I type in.
In the file code.gs:
function doGet () {
var participant = {};
var templ = HtmlService.createTemplateFromFile('out');
return templ.evaluate();;
}
function formSubmit(name) {
Logger.log("name " + name);
}
In out.html
<!DOCTYPE html>
<html>
<head>
<base target ="_top">
</head>
<body dir="rtl"; background-color: #92a8d1;>
<label> Name 1 </label> <input type="text" id="firstname"><br>
<label> Name 2 </label> <input type="text" id="lastname"> <br><br>
<button type="button" id="send">Send</button>
<script>
document.getElementById("send").addEventListener("click", getData());
function getData(){
var uname = document.getElementById("firstname").value;
google.script.run.formSubmit(uname);
}
</script>
</body>
</html>
You want to retrieve the value of <input type="text" id="firstname"> when the button is clicked.
In your current situation, when you see the log with the script editor, only name is retrieved. This is your current issue.
You want to know the reason of the issue.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
In your script, document.getElementById("send").addEventListener("click", getData()); is used. In this case, when the HTML is loaded, getData() is run by () of getData(). By this, uname becomes "" and "" is sent to formSubmit(uname), then, when you see the log, you see name. And also, in this case, even when the button is clicked, google.script.run.formSubmit(uname); cannot be run. I think that this is the reason of the issue of your script in your question.
In order to avoid this, please modify your script as follows.
Modified script:
From:
document.getElementById("send").addEventListener("click", getData());
To:
document.getElementById("send").addEventListener("click", getData);
By the above modification for your script, when sample is inputted to "Name 1" and click "Send" button, you can see name sample at the log with the script editor.
Reference:
addEventListener()
If I misunderstood your question and this was not the result you want, I apologize.
Here's an example form that you can probably use to accomplish your needs. This form is used as a simple receipt collection system. You can actually take and upload images from a mobile device with it. I also has text and button input types and upload a form node.
Code.gs
var receiptImageFolderId='';
var SSID='';
function onOpen() {
SpreadsheetApp.getUi().createMenu('Receipt Collection')
.addItem('Run as Dialog', 'showAsDialog')
.addItem('Run as Sidebar', 'showAsSidebar')
.addToUi();
var sh=SpreadsheetApp.getActive().getSheetByName("Sheet1");
sh.getRange(sh.getLastRow()+1,1).activate();
}
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Sheet1').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function doGet() {
var output=HtmlService.createHtmlOutputFromFile('receipts').setTitle('thehtml');
return output.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).addMetaTag('viewport', 'width=360, initial-scale=1');
}
function showAsDialog() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showModelessDialog(ui, 'Receipts')
}
function showAsSidebar() {
var ui=HtmlService.createHtmlOutputFromFile('thehtml');
SpreadsheetApp.getUi().showSidebar(ui);
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd")
return {date:datestring};
}
The Html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<br /><input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
</body>
</html>
Here's what the dialog looks like:
Related
I have created a fillable HTML form that can be opened from a custom menu within a Google Spreadsheet. The form is opening as expected, and the onSuccess() script is executing. The issue I am having is that the values are not being added to the spreadsheet.
Here is the .gs file:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom')
.addItem('New Entry', 'openForm')
.addToUi();
}
function openForm() {
var html = HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'New Entry');
}
function AddToSheet(InputOne, InputTwo, InputThree) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet_Name');
sheet.appendRow([InputOne, InputTwo, InputThree]);
}
And here is the HTML file (index.html)
<html>
<body>
<div>
<form>
<fieldset>
<input type="text" id="fieldA" name="Field 1">
<input type="number" id="fieldB" name="Field 2">
<input type="text" id="fieldC" name="Field 3">
<input type="button" value="Save Input" onclick="WriteInput()">
<input type="reset" value="Reset">
</fieldset>
</form>
</div>
<script>
function onFailure(error) {
alert(error.message);
}
</script>
<script>
function onSuccess() {
alert("Your INPUT was SAVED!");
}
</script>
<script>
function WriteInput() {
var strngOne = document.getElementById("fieldA").value;
var strngTwo = document.getElementById("fieldB").value;
var strngThree = document.getElementById("fieldC").value;
google.script.run.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.AddToSheet(strngOne, strngTwo, strngThree);
}
</script>
</body>
</html>
I'm not sure exactly what the issue is. Everything is working as expect for the values appending to the Spreadsheet.
Thanks in advance for your help!
<!DOCTYPE html>
<html>
<head>
<title>WhiteList</title>
</head>
<body>
<h1>Hello stranger lets see if you are on the list!!</h1>
<input id="1" value="type here" placeholder="type here">
<button onclick="click()">Check</button>
<br>
<p id=stuff></p>
<script type="text/javascript">
function click(){
var name = document.getElementById('1').value;
if (name == "tijmen"){
document.getElementById("stuff").innerHTML = "<p>hey you are on the list welcome</p>"
} else{
document.getElementById("stuff").innerHTML = "<p>sorry you are not on the list</p>"
}
}
</script>
</body>
</html>
so this is the code, there are no errors. but the problem is that the text won't print when i insert my name and click the button.... i realy cant seem to find the problem.
Try add onclick to the JavaScript:
<body>
<h1>Hello stranger lets see if you are on the list!!</h1>
<input id="1" value="type here" placeholder="type here">
<button id="btn">Check</button>
<br>
<p id=stuff></p>
<script type="text/javascript">
document.getElementById("btn").onclick = function() {
var name = document.getElementById('1').value;
if (name === "tijmen"){
document.getElementById("stuff").innerHTML = "<p>hey you are on the list welcome</p>"
} else {
document.getElementById("stuff").innerHTML = "<p>sorry you are not on the list</p>"
}
}
</script>
</body>
Problem here is click is defined as a click action so the engine is thinking you are calling the click of the button. Simple test shows what the browser sees.
<button onclick="console.log(click)">Check</button>
What can you do? Change the name, or even better, use addEventListener to bind the event listener.
Hey guys what am I doing wrong here?? I'm sorry if this has been posted before, but I couldn't find a good example with a form input.
Thank you.
I really don't understand why output.value.toUpperCase() doesn't work, or toUpperCase(output.value) wouldn't work.
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Barlow" rel="stylesheet">
</head>
<body>
<h1 id="title">Capitalize a String</h1>
<form>
<input type="text" id="entry" placeholder="Enter a string to be capitalized">
</form>
<h1 id="title">Output</h1>
<form>
<input type="text" id="output" placeholder="Output">
</form>
<div id="goBtn">
<h1 id="goBtnText">
GO
</h1>
</div>
</body>
</html>
var goBtn = document.getElementById('goBtn');
var entry = document.getElementById('entry');
var output = document.getElementById('output');
goBtn.addEventListener('click', capitalizeStr);
function capitalizeStr () {
output.value = entry.value;
return output.value.toUpperCase();
}
You will need to do
function capitalizeStr () {
output.value = entry.value.toUpperCase();
}
Calling output.value.toUpperCase() does not change the output.value property, it just returns a new string (and the value returned by an event listener is ignored).
I'm new with javascript so hopefully what I want would work.
I checked a few forums and tutorials and most of them only teaches things like
<p>Original name: <span id="origname"></span></p>
<p>New name: <span id="newname"></span></p>
<script>
var employees = [
{ "firstName" : "John" , "lastName" : "Doe" },
{ "firstName" : "Anna" , "lastName" : "Smith" },
{ "firstName" : "Peter" , "lastName" : "Jones" }, ];
document.getElementById("origname").innerHTML=employees[0].firstName + " " + employees[0].lastName;
// Set new name
employees[0].firstName="Gilbert";
document.getElementById("newname").innerHTML=employees[0].firstName + " " + employees[0].lastName;
</script>
which is pretty understandable but I just want to do something as simple as input a text field then submit and within the same page at the bottom will show whatever the text is being inputted.
I wonder if anyone can give me a hand with this.
the above is what I want...
EDITED
This is what I have at the moment after getting the replies from all the nice people and the script makes sense to me but somehow it's still not working though :(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>
<form action=" " method="post">
<input id="myInput" type="text"/>
<input id="myButton" type="button" value="submit"/>
<p id="myOutput"></p>
</form>
<script>
$("#myButton").click(function() {
var data = $("#myInput").val();
$("#myOutput").val(data);
});
</script>
</body>
additional question out of the blue.
let's say at the moment my code is
<p id="myOutput" style="color: yellow; background: black; width: 100px;"></p>
is jquery able to change the codes?
let's say if somehow I type red then the code would be
<p id="myOutput" style="color: red; background: black; width: 100px;"></p>
and if I have another input text area and input 200 then the code would be
<p id="myOutput" style="color: yellow; background: black; width: 200px;"></p>
something like that....
Based on the picture you supplied, I would approach this using AJAX for the data submission and then jQuery to update/reflect a <div> on the page (#3 in your pic).
You might already know how to do the above but if not, I found these tutorials extremely helpful when learning AJAX and updating div's with jQuery:
Handling a form with AJAX: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Then updating a <div> on your page using the success function when AJAX is done: http://api.jquery.com/jQuery.ajax/
However, if you don't actually need to process the data...then just use JQUERY to handle all of it! Normal form, then use the below to update the DIV with the data onclick of submit.
<div id="output"></div>
<script>
$("#submit").click(function() {
var output = $("#new_name").val();
$("#output").text(output);
});
</script>
UPDATED
Thanks for posting the code. I fiddled a working solution here http://jsfiddle.net/hwGde/4/
And here is the code with the comment on the line that had the issue:
<form action=" " method="post">
<input id="myInput" type="text" />
<input id="myButton" type="button" value="submit" />
<p id="myOutput"></p>
</form>
<script>
$("#myButton").click(function () {
var data = $("#myInput").val();
// $("#myOutput").val(data); this should be .text instead of .val
$("#myOutput").text(data);
});
</script>
Let me know how this works. And don't forget to mark it as the answer (if it works) for future users. Thanks!
you can do this by,
<input type="text" id="name2" onclick="changeName()" />
<script>
function changeName(){
document.getElementById('newname').innerHTML=document.getElementById('name2').value;
}
</script>
If you use jquery to write less do more,
<input id="myInput" type="text"/>
<input id="myButton" type="button"/>
<p id="myOutput"></p>
<script>
$("#myButton").click(function() {
var data = $("#myInput").val();
$("#myOutput").val(data);
});
</script>
Additionally take a look at knockout, you can do such things easier when there are lots of situations like yours in a page.
If you use knockout
<input type="text" data-bind="value:data"></input>
<p data-bind="text:data"></p>
<script>
function AppViewModel() {
this.data= ko.observable("");
}
ko.applyBindings(new AppViewModel());
</script>
I am using UIWebView in iPhone and loaded one HTML page from resources.
Following is my HTML page code:
<html>
<head>
<title></title>
<SCRIPT language="JavaScript">
function callme(id)
{
var input = 'input'+id;
document.getElementById(input).value = document.getElementById('code').value;
}
</SCRIPT>
</head>
<body>
<input type=hidden id='code' name='code'>
<a href="#" id="click1" name="click1" onclick='callme(1);'>Click1</a>
<input type="text" id="input1" name="input1">
</br>
<a href="#" id="click2" name="click2" onclick='callme(2);'>Click2</a>
<input type=text id="input2" name="input2">
</br>
<a href="#" id="click3" name="click3" onclick='callme(3);'>Click3</a>
<input type=text id=input3 name=input3>
</body>
</html>
I have inject some Javascript on page using following code:
[webView stringByEvaluatingJavaScriptFromString:#"var field1 = document.getElementById('code'); field1.value='Code010203';"];
What I want is when user click on link first injected script should run and then onclick event's function(callme(1) or 2 or 3) for link(Click1,Click2 or Click3) should execute.
function callme(id)
{
injectedCode();
var input = 'input'+id;
document.getElementById(input).value = document.getElementById('code').value;
}
where injected code is:
[webView stringByEvaluatingJavaScriptFromString:#"var field1; function injectedCode() {field1 = document.getElementById('code'); field1.value='Code010203';}"];
I'm not 100% sure I understand your question.
If you want the click event to run the injected code, would this approach work for you :
(this is the injected code below)
document.querySelector("#click1").onclick = function() {
// do your new stuff here
clickMe(1);
};
You could make this generic with a bit of effort e.g.
document.querySelector("a[id^=click]").onclick = function() {
// do your new stuff here
var clickMeArg = this.id.substring("click".length);
clickMe(parseInt(clickMeArg, 10));
};