Webapp button to duplicate sheet in google sheets - dom

I'm trying to create a simple webapp button that it will duplicate sheet in Google sheets , I created the button in HTML and linked it to run the code when its clicked ! but it doesnt seem to work !, can someone tell me what I did wrong ?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="btn">Create</button>
<script>
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
google.script.run.userClicked();
}
</script>
</body>
</html>
And here is the code for duplication :
function doGet() {
return HtmlService.createHtmlOutputFromFile('page');
}
function userClicked() {
SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
var myValue = SpreadsheetApp.getActiveSheet().getRange("M1").getDisplayValue();
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Daily Report " + myValue);
}

Duplicating & Deleting Sheets from a WebApp
Code.gs:
function dupSheet(dObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.setActiveSheet(ss.getSheetByName(dObj.name));
ss.duplicateActiveSheet();
var name="Daily Report " + sh.getRange("A1").getDisplayValue();
if(!sheetExists(name)) {
ss.renameActiveSheet("Daily Report " + sh.getRange("A1").getDisplayValue());
}
dObj['sA']=getSheetNames().sA;
return dObj;
}
function getSheetNames() {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var sObj={sA:[]};
shts.forEach(function(sh){
sObj.sA.push(sh.getName());
})
return sObj;
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('dup');
}
function delSheet(dObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(dObj.name);
ss.deleteSheet(sh);
dObj['sA']=getSheetNames().sA;
return dObj;
}
function sheetExists(name) {
var ss=SpreadsheetApp.getActive();
var sA=ss.getSheets();
for(var i=0;i<sA.length;i++) {
if(name==sA[i].getName()) {
return true
}
}
return false;
}
dup.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
function dupSheet() {
$("#sel1").css('background-color','#ffff00');
google.script.run
.withSuccessHandler(function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.dupSheet({name:$('#sel1').val()});
}
function delSheet() {
$("#sel1").css('background-color','#ffff00');
google.script.run
.withSuccessHandler(function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select A File Name');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.delSheet({name:$('#sel1').val()});
}
</script>
<style>
input{margin:2px 5px;}
</style>
</head>
<body>
<select id="sel1"></select><label for="sel1">Sheet Name</label>
<br /><input type="button" value="Duplicate Sheet" onClick="dupSheet();" />
<br /><input type="button" value="Delete Sheet" onClick="delSheet();" />
</body>
</html>
I used a little JQuery in there too.

As stated in the SpreadsheetApp reference.
getActiveSheet()
Gets the active sheet in a spreadsheet. The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.
Since you are not using any UI you should instead use other methods of accessing your Sheets and Spreadsheets, such as:
Obtaining your Spreadsheet
SpreadsheetApp.openById(id)
SpreadsheetApp.openByUrl(url)
Obtaining your Sheet(s)
Spreadsheet.getSheetByName(name)
Spreadsheet.getSheets()

Related

JS window.onload doesn't load my function

I've got JS form validation code and have to write HTML to it. Unfortunately, something is wrong. Could you please tell me what I am doing wrong? When I click submit button there is no change.
window.onload = init;
function validateForm() {
var user = document.forms["myForm"]["user"].value;
var password = document.forms["myForm"]["password"].value;
if (user == "") {
document.getElementById("poleUser").innerHTML = "<img src='./unchecked.gif'/> Proszę podać nazwisko";
} else {
document.getElementById("poleUser").innerHTML = "<img src='./checked.gif'/>";
}
if (password.lenght < 6) {
document.getElementById("poleHasla").innerHTML =
"<img src='./unchecked.gif'/> Hasło musi zawierać co najmnej 6 znaków";
} else {
document.getElementById("poleHasla").innerHTML = "<img src='./checked.gif'/>";
}
return false;
}
function init() {
document.getElementsByName('myForm').onsubmit = validateForm;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="myForm">
Name: <input type="texts" name="user"><span id="poleUser"></span><br>
Password: <input type="password" name="password"><span id="poleHasla"></span>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
You need to properly format the function calls
document.getElementsByName('myForm').onsubmit = validateForm;
should be
document.getElementsByName('myForm').onsubmit = validateForm();
(Notice the parentheses at the end).
However, I'd just like to address how you're doing this. In most cases, assigning the onSubmit property statically makes more sense than doing it dynamically. In this case, there really doesn't seem to be any reason for initializing the property using JS.

Highlight Dates dynamically of datetimepicker - The plugin used for datepicker is Jquery datetimepicker full

$("#myDate").datetimepicker({
timepicker: false,
format: 'Y-m-d',
scrollInput: false,
value: new Date(),
onChangeDateTime: function (dp, $input) {
LoadBasedOnDate();
}
,
highlightedDates: [
dateArray[0]
]
});
dateArray contains a set of dates as array for example [ "2020-03-17" "2020-03-18","2020-03-20"]
Here dateArray[0] , "2020-03-17" is highlighted .
How can highlight every date from dateArray in datepicker? jquery datetimepicker full plugin is
used
Here is the answer to your question. You need to use beforeShowDay function in the jquery ui datepicker. In that you can compare all dates with your dateArray. Add css-class-to-highlight this class if match is found.
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$(function () {
var dateArray = [ "2020-03-17", "2020-03-18","2020-03-20"];
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
beforeShowDay: function (date) {
// First convert all values in dateArray to date Object and compare with current date
var dateFound = dateArray.find(function(item) {
var formattedDate = new Date(item);
return date.toLocaleDateString() === formattedDate.toLocaleDateString();
})
// check if date is in your array of dates
if(dateFound) {
// if it is return the following.
return [true, 'css-class-to-highlight', 'tooltip text'];
} else {
// default
return [true, '', ''];
}
}
});
});
</script>
<style type="text/css">
.css-class-to-highlight a{
background-color: blue !important;
color: #fff !important;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="NonBusinessDays" />
<div id="datepicker"></div>
</div>
</form>
</body>
</html>

Rest, ngresource, $resource not returning anything

I'm trying to GET Rest data from a parse.com backend with Angularjs. I expect at least console log you can see in the code below to return something, but it returns nothing, and there are no error in the console.
Here is the code i'm trying:
Full Javascript code:
var todoApp = angular.module('todoApp', ['ngResource']);
todoApp.factory('todoFactory', function($resource) {
return $resource('https://api.parse.com/1/classes/Professional', {}, {
method: 'GET',
headers: { 'X-Parse-Application-Id':'xxx', 'X-Parse-REST-API-Key':'yyy'}
});
});
function TodoController($scope, $location, todoFactory) {
function loadTodos() {
$scope.items = todoFactory.query();
console.log(todoFactory.query()); //i expect this to log something at least
}
}
Full html code:
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title></title>
</head>
<body>
<div ng-controller="TodoController">
<ul>
<li ng-repeat="item in items"> {{item.firstName}} </li>
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js"></script>
Any clue on how to give life to this dead code ?
The problem is that you are not calling your function.
You have two options:
In your controller:
function TodoController($scope, $location, todoFactory) {
function loadTodos() {
$scope.items = todoFactory.query();
console.log(todoFactory.query());
}
// You declare the function, now you can use this
loadTodos();
}
But, in this way, the function isn't available in your view, because it isn't declared in the $scope. To that, you should declare like this:
function TodoController($scope, $location, todoFactory) {
$scope.loadTodos = function() {
$scope.items = todoFactory.query();
console.log(todoFactory.query());
}
}
You declare the function in $scope, now you can use in the view like this:
<button type="button" ng-click="loadTodos()">Get Items</button>

drop event is not fired

In the application below, the drop method is never called. The drop target (div2) is indicated by cancelling event in dragEnter and dragOver events but drop is not triggered. HTML and .dart are as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dandd</title>
<link rel="stylesheet" href="dandd.css">
</head>
<body>
<h1>Drag and drop</h1>
<p>Hello world from Dart!</p>
<div>
<label id='lbl' draggable='true' style='border: 1px solid; '>div1</label>
</div>
<p></p>
<div id='div2'>
<label>div2</label>
</div>
<script type="application/dart" src='dandd.dart > </script>
<script type='text/javascript'
src="https://dart.googlecode.com/svn/branches/bleeding_edge/dart/client/dart.js"></script>
</body>
</html>
and here is dart file
import 'dart:html';
void main() {
query('#lbl')
..on.dragStart.add(onDragStart)
..on.dragEnd.add(onDragEnd);
query('#div2')
..on.dragEnter.add(onDragEnter)
..on.dragOver.add(onDragOver)
..on.drop.add(onDrop);
query('#div2')
..on.dragLeave.add(onDragLeave);
}
onDragStart(MouseEvent e) {
print('started');
var lbl = e.target as LabelElement;
lbl.style.opacity = '0.4';
e.dataTransfer.setData('text', lbl.id);
}
onDragEnd(MouseEvent e) {
var lbl = e.target as LabelElement;
lbl.style.opacity = '1.0';
print('drag end called');
}
onDragEnter(MouseEvent e) {
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
var x = e.target as DivElement;
x.classes.add('blueborder');
}
onDragOver(MouseEvent e) {
e.stopPropagation();
e.dataTransfer.dropEffect = 'move';
var x = e.target as DivElement;
x.classes.add('blueborder');
}
onDragLeave(MouseEvent e) {
var x = e.target as DivElement;
x.classes.remove('blueborder');
}
onDrop(MouseEvent e){
print('on drop called');
var x = e.target as DivElement;
x.classes.remove('blueborder');
String sid = e.dataTransfer.getData('text');
var v = query('#{sid}');
x.children.add(v);
}
It looks like a bug. See issue 6646.

iphone phone gap application using javascript

In my iPhone phonegap application I want to capture image using camera of device.I have done with the following code but it not works.Am not able to capture image.
In the following code in HTML section i have one button and when it clicked then i will call method defined of java script.
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
function onLoad() {
document.addEventListener("deviceready",onDeviceReady,false);
}
// PhoneGap is ready to be used!
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved (taken with camera)
function onPhotoDataSuccess(imageData) {
alert("Your photo was taken successfully.");
}
// Called when a photo is successfully retrieved (out of the device's library)
function onPhotoURISuccess(imageURI) {
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="file";
//options.fileName="newfile.txt";
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://www.yourdomain.com/upload.php", win, fail, options);
// Make sure you use your own site!
}
// Success reporting
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
}
// Error reporting
function fail(message) {
alert('Failed because: ' + message);
}
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, fail, { quality: 30 });
}
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, fail, {
quality: 30,
destinationType: destinationType.FILE_URI,
sourceType: source
});
}
</script>
</head>
<body onload="onLoad()">
<button onclick="capturePhoto();">Take a Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Upload a Photo</button>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
will you please try with the following snippet.
It capture the image from camera and also load in img tag. I tested on device.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PGCamera</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function PictureSourceType() {};
PictureSourceType.PHOTO_LIBRARY = 0;
PictureSourceType.CAMERA = 1;
function getPicture(sourceType){
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData){
alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()">
<img style="width:60px;height:60px" id="test_img" src="" />
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
thanks,
Mayur