Goole App Script HTML Onclick Button Issue - google-apps-script

I am working on a sidebar menu, and so far, I got it working to load values from a sheet. I am working on getting the sidebar to update the value that is selected and currently struggling a little bit since I can't seem to catch an error and struggling a bit to figure out how to error handle app scripts and HTML in app scripts. So the first ask here is can someone point me to a reference on how to error handle issues with HTML and Apps script.
My second issue my current problem, I have an HTML button that is calling onFormUpdate() function which is located inside a seperate HTML file just for handling javascript functions. Here is my index.html
<!DOCTYPE html>
<html>
<base target="_top">
<?!= include('sidebar/sidebarcss'); ?>
<body>
<div id="title">
<div><h2>Meeting Item</h2></div>
</div>
<div id="meet">
<form id="meetform">
Row ID: <br>
<input type="text" id="meetrowId" name="meetrowId" maxlength="4" size="4" readonly />
Meet ID: <br>
<input type="text" id="meetId" name="meetId" maxlength="8" size="10" readonly />
Enter Date: <br>
<input type="text" id="meetingDate" name="meetingDate"/>
Topic: <br>
<input type="text" id="meetTopic" name="meetTopic"/>
Agenda: <br>
<textarea name="meetAgenda" id="meetAgenda" rows="10" cols="30"></textarea>
Comment History:<br>
<textarea name="meetComments" id="meetComments" rows="10" cols="30" readonly ></textarea>
Add Comments:<br>
<textarea name="meetComUpdate" id="meetComUpdate" rows="10" cols="30"></textarea><br>
<input type="button" class="button" value="Update Record" onclick="onFormUpdate()"/>
</form>
</div>
<input type="button" class="button" value="Select Another ID" onclick="google.script.run.showEmailSidebar()"/>
<input type="button" class="button" value="Close" onclick="google.script.host.close()"/>
<?!= include('sidebar/script'); ?>
<script>
google.script.run.withSuccessHandler(onSuccess).SidebarActiveRow();
</script>
</body>
</html>
Within the form i call my onFormUpdate() and nothing happens when I click the button. As you can see i include 'sidebar/script' which is my html file that stores all javascript functions. OnFormUpdate() is located within the 'sidebar/script' and is shown below:
<script>
function onSuccess([cellrow, meetid, meetdate, meettopic, meetagenda, meetcomments])
{
/*
Secondary method for string parsing
const table =sidebarVar.split(",") //["key:value","key:value"]
.map(pair => pair.split(":")); //[["key","value"],["key","value"]]
const result = Object.fromEntries(table);
result.meetid;
*/
document.getElementById('meetrowId').value = cellrow
document.getElementById('meetId').value = meetid
document.getElementById('meetingDate').value = meetdate
document.getElementById('meetTopic').value = meettopic
document.getElementById('meetAgenda').value = meetagenda;
document.getElementById('meetComments').value = meetcomments;
}
function onFormUpdate()
{
var recordform =
{
row: document.getElementById('meetrowId').value,
topic: document.getElementById('meetTopic').value,
agenda: document.getElementById('meetAgenda').value,
newcomment: document.getElementById('meetComUpdate').value
};
google.script.run.withSuccessHandler(SidebarActiveRow).recordUpdate(recordform);
}
</script>
As you can see I am trying to get the app handler to call SidebarActiveRow which is leverage with my onSuccess function to load data elements from the sheet; this works fine. The handler is calling SidebarActiveRow to run after i successfully run recordUpdate() which is located in my code.gs file. So far nothing is happening. I have this current code for testing to see if the function works but no success.
function recordUpdate(recordform) {
SpreadsheetApp.getUi().alert(recordform.row);
}
I get no prompts which I can't seem to troubleshoot since the html and Apps Script function don't really show an errors. I did go to executions to see if there were any errors and i don't see any at this time. So i am looking for some help here.

Look at javascript Error Handling.
For HTML:
<script>
function someFunction() {
try {
// ... do some code
}
catch(err) {
alert(err);
}
}
</script>
For App Script
function someFunction() {
try {
// ... do some code
}
catch(err) {
Logger.log(err); // check execution log
}
}

Related

How to trigger HTML5 validation error on button click

I have a form which done in 3 steps. In first 2 steps validation errors doesn't showing because they have no submit button. How I trigger errors here?
So here's piece of code that will do your job....
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ //do this only after the whole thing is loaded, use this for more complex error handles...
$('#form_').submit(function(data){ //this is triggered once you try to submit your data
var Nerror = 0; //we declare the number of errors
if($('#name_input').val()==''){ //here is where you handle errors, checking whether or not you
$('#name_input').addClass('has-error');
$('#name_input').val('');
Nerror++; //increment +1 to Nerror
alert('no name');
}
if($('#lname_input').val()==''){
$('#lname_input').addClass('has-error');
$('#lname_input').val('');
Nerror++;
alert('no last name');
}
if(Nerror>0){ //if Nerror is bigger then zero, we use the .preventDefault method to make sure the form is not submited
data.preventDefault();
}
});
});
</script>
<body>
<form id='form_' action='your_next_step.php' method='post'>
<input type='text' name='name' id='name_input' required> <!-- if you wish to make the inputs required, just put "required" inside the tags... -->
<input type='text' name='lastname' id='lname_input' required>
<button type='submit'>Next</button>
</form>
</body>
I hope you can do it now, if you have more complex handlers like checking your database for equal entries then you need to create a php file that makes that for you, then return the result in JSON or something....
Good luck.

Id duplicates when using templates in parse / backbone / js / html

I get duplicate ids when I set the views like so in my render function
var template = _.template($("#user-login-template").html(), {});
this.$el.html(template);
The html looks like this after running the render function, before runing the render function. Beforehand, the <div class ="app"> is empty (as it should be). It copy pasted the code from template and therefore the ids into the div.
<div class="app">
<input type="text" id="signup-username" placeholder="Username"/>
<input type="password" id="signup-password" placeholder="Create a Password"/>
<button id="signUpBtn">Sign Up</button>
<button id="logInBtn">Login</button>
</div>
<!-- Templates -->
<!-- Login Template -->
<script type="text/template" id="user-login-template">
<input type="text" id="signup-username" placeholder="Username"/>
<input type="password" id="signup-password" placeholder="Create a Password"/>
<button id="signUpBtn">Sign Up</button>
<button id="logInBtn">Login</button>
</script>
For reference, this is what my whole view looks like
var LogInView = Parse.View.extend({
el: '.app',
events: {
"click .signUpBtn": "signUp",
"click .logInBtn": "logIn"
},
initialize: function (){
this.render()
},
logIn: function () {
//To Do
},
render: function () {
var template = _.template($("#user-login-template").html(), {});
this.$el.html(template);
}
});
If Webstorm is complaining about the ids inside the <script> then it is wrong and you have three options:
Get a new IDE that has a better understanding of HTML.
Figure out how to reconfigure Webstorm to know what HTML really is. There must be a way to beat some sense into Webstorm, this sort of thing is very common these days.
Ignore the warnings (yuck).
Things inside <script> are not HTML and are not part of the DOM. Ask the browser what $('input[type=text]').length is after your template is rendered and you'll get 1 since the
<input type="text" id="signup-username" placeholder="Username"/>
inside the <script> isn't HTML, it is just text. You can even check the HTML specification of <script>:
Permitted contents
Non-replaceable character data
Non-replaceable character data is not HTML, it is just text.

HTML - How to do a Confirmation popup to a Submit button and then send the request?

I am learning web development using Django and have some problems in where to put the code taking chage of whether to submit the request in the HTML code.
Eg. There is webpage containing a form(a blog) to be filled by the user, and upon click on the Save button,there is a pop up asking whether you want to confirm or not. If click on confirm, then the request is sent.
I searched and find this javascript code.
<script type="text/javascript">
function clicked() {
alert('clicked');
}
<input type="submit" onclick="clicked();" value="Button" />
But I guess this is not the correct function as it seems to me that whenever you click on the Button, the request will be submitted. So How can I delay the submit request until user has confirm the submit?
The most compact version:
<input type="submit" onclick="return confirm('Are you sure?')" />
The key thing to note is the return
-
Because there are many ways to skin a cat, here is another alternate method:
HTML:
<input type="submit" onclick="clicked(event)" />
Javascript:
<script>
function clicked(e)
{
if(!confirm('Are you sure?')) {
e.preventDefault();
}
}
</script>
I believe you want to use confirm()
<script type="text/javascript">
function clicked() {
if (confirm('Do you want to submit?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
Use window.confirm() instead of window.alert().
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
<script type='text/javascript'>
function foo() {
var user_choice = window.confirm('Would you like to continue?');
if(user_choice==true) {
window.location='your url'; // you can also use element.submit() if your input type='submit'
} else {
return false;
}
}
</script>
<input type="button" onClick="foo()" value="save">
For a Django form, you can add the confirmation dialog inside the form tag:
<form action="{% url 'delete' %}" method="POST" onsubmit="return confirm ('Are you sure?')">
Another option that you can use is:
onclick="if(confirm('Do you have sure ?')){}else{return false;};"
using this function on submit button you will get what you expect.

show JSON in new window

I have a problem with json. I'd like to display the result of my form in the new browser window in JSON. (When user fills all fields in the form, button becomes enabled and shows JSON in specified format (I did it)). I translated it in JSON but dunno how to output it...I'm thinking of create new html page and do window.open on button on 1st page, but then it doesn't read data from 1st page which user entered. Or should I save it somehow in JSON file and then read it from other page?
For example:
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button type="submit" id="btn" class="btn" disabled="disabled">Submit</button>
</form>
I have some form with date field and button:
I can easily get JSON of date field by {{date | json}} on the same page, but I just want to output it in new browser window. How can I do this? Please help me with some tips. Thanks.
If it's not too big you can send the information to the new window as a data URL.
The frame will be reused once it is open.
This might be a start, showing how to plug in the JSON data and break it up over multiple lines for display.
window.open('data:application/json,'
+JSON.stringify(location).replace(/([[{,])/g, "$1%0a"),
'jsonFrame',
'resizeable,top=100, left=100, height=200, width=300,status=1')
See MDN for all the details.
You should be able to get at the window.opener from the new window and parse values out of it. The following plunker shows storing data from the current scope in an accessible area when the controller's submit is clicked. From the new window it then parses the content from the opener into the window's scope for further processing.
http://plnkr.co/edit/OkKX5zxYVSoZ7w81WV8J?p=preview
You'll notice here too how to get an angular friendly way of calling the submission and the disabling of the button until ready.
Hope this helps.
How about to save your input data into a cookie on one page and then get it via JavaScript when you will open a new window?
I could prepare the code in jsFiddle, but seems like it does not import external resources at this moment. So I'll post it here:
page 1:
...
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input id="date" type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button id="btn" class="btn" >Submit</button>
</form>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#btn').click( function() {
var cookie_value = $('#inut_test').val();
/*cookie_value should be your json string*/
$.cookie("json_cookie", cookie_value, { path: '/' });
window.open("http://localhost/page2");
return false;
});
</script>
...
page 2:
...
<a id="see-cookie" href="#">
click me!!!
</a>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#see-cookie').live('click', function() {
alert($.cookie('json_cookie'));
return false;
});
</script>
...
Do not forget about { path: '/' } cookie property to set it for all site and about including jQuery cookie library into your page.

form htmlservice issue with passing parameters

I have looked at other posts and am struggling with the same issue of how to pass form values to GAS. Since GUI editor has been depreciated, I decided to go the htmlservice form route. In this simple code below, I'm just trying to access the form field aField and paste it in a cell.
function doGet() {
return HtmlService.createHtmlOutputFromFile('myForm.html');
}
function processForm(value) {
var myRange = SpreadsheetApp.openById("xxx").getSheetByName("Results-List").getDataRange("B20");
myRange.setValue(value.aField);
}
This is the HTML template myForm.html:
<html>
<form id="myForm">
<input name="aField" id="aField">
<input type="button" id="submit" value="submit" onclick = "sendData()">
</form>
<script>
function sendData() {
google.script.run.processForm(document.getElementById("myForm"));
}
</script>
</html>
.getDataRange() has a different use. Use .getRange('B20') to get this to work.