Passing data to variables from other Javascript files - javascript

I'm working on a project that is driving me crazy, I've searched through the articles here on the site but I've not been able to get it into my head how to make this work.
I am using a Modernizr.js file to check for Geolocation and localStorage, the localStorage piece is working fine as well as finding the latitude, longitude and creating a map with the geolocation file. The issue I'm having is passing the latitude and longitude values back to the main js file so that I can pass those values (along with the form data entered on the page) into a constructor function.
I don't know if it is the order of my statements or if I am passing the data incorrectly, I've been battling this for a while now and have only succeeded in confusing myself more. If anyone can help to clarify this for me I would greatly appreciate it.
I am including all files for this project, again am only stuck on passing the values for the latitude and longitude back from the geolocation.js file.
HTML File:
<!doctype html>
<html>
<head>
<title>JavaScript, Ajax and JSON: To Do List</title>
<meta charset="utf-8">
<link rel="stylesheet" href="toDoL14O2.css">
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="Modernizr.js"></script>
<script>
Modernizr.load([
"toDoL14O2.js",
{
test: Modernizr.geolocation,
yep: "L14O2geolocation.js",
nope: "L14O2noGeolocation.js"
},
{
test: Modernizr.localstorage,
yep: "L14O2localStorage.js",
nope: "L14O2noLocalStorage.js",
complete: function() {
init();
}
}
]);
</script>
</head>
<body>
<div>
<h1>My To Do List</h1>
<ul id="todoList">
</ul>
<!-- display the map//-->
<div id="mapDiv">
<h1>Where To Do It</h1>
<div id="map">
</div>
</div>
<!-- display the search results //-->
<div id="searchResults">
<h2>Results</h2>
<ul id="searchResultsList">
</ul>
</div>
<form>
<!-- display the search input //-->
<fieldset>
<legend>Search to do items</legend>
<div class="tableContainer">
<div class="tableRow">
<label for="searchTerm">Search: </label>
<input type="text" id="searchTerm" size="35"
placeholder="search term">
</div>
<div class="tableRow">
<label for="searchButton"></label>
<input type="button" id="searchButton" value="Search">
</div>
</fieldset>
<fieldset>
<legend>Add a new to do item</legend>
<div class="tableContainer">
<div class="tableRow">
<label for="task">Task: </label>
<input type="text" id="task" size="35" placeholder="get milk">
</div>
<div class="tableRow">
<label for="who">Who should do it: </label>
<input type="text" id="who" placeholder="Scott">
</div>
<div class="tableRow">
<label for="dueDate">Due Date: </label>
<input type="date" id="dueDate" placeholder="mm/dd/yyyy">
</div>
<div class="tableRow">
<label for="submit"></label>
<input type="button" id="submit" value="submit">
</div>
</fieldset>
</form>
</div>
</body>
</html>
toDo JavaScript File:
function Todo(id, task, who, dueDate, days, lat, lon) {
this.id = id;
this.task = task;
this.who = who;
this.dueDate = dueDate;
this.done = false;
this.days = days;
this.lat = lat;
this.lon = lon;
}
var todos = new Array();
var lat;
var lon;
console.log("Before Onload: " + lat + ", " + lon);
window.onload = init;
function init() {
var submitButton = document.getElementById("submit");
submitButton.onclick = getFormData;
// get the search term and call the click handler
var searchButton = document.getElementById("searchButton");
searchButton.onclick = searchTodos;
getTodoItems();
}
function getTodoItems() {
if (localStorage) {
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.substring(0, 4) == "todo") {
var item = localStorage.getItem(key);
var todoItem = JSON.parse(item);
todos.push(todoItem);
}
}
addTodosToPage();
}
else {
console.log("Error: you don't have localStorage!");
}
}
function addTodosToPage() {
var ul = document.getElementById("todoList");
var listFragment = document.createDocumentFragment();
for (var i = 0; i < todos.length; i++) {
var todoItem = todos[i];
var li = createNewTodo(todoItem);
listFragment.appendChild(li);
}
ul.appendChild(listFragment);
}
function addTodoToPage(todoItem) {
var ul = document.getElementById("todoList");
var li = createNewTodo(todoItem);
ul.appendChild(li);
document.forms[0].reset();
}
function createNewTodo(todoItem) {
var li = document.createElement("li");
li.setAttribute("id", todoItem.id);
var spanTodo = document.createElement("span");
spanTodo.innerHTML =
todoItem.who + " needs to " + todoItem.task + " by " +
todoItem.dueDate + " at Lat: " + todoItem.lat + " & Lon: " +
todoItem.lon + "Task has " + todoItem.days + " days until due";
var spanDone = document.createElement("span");
if (!todoItem.done) {
spanDone.setAttribute("class", "notDone");
spanDone.innerHTML = " ";
}
else {
spanDone.setAttribute("class", "done");
spanDone.innerHTML = " ✔ ";
}
// add the click handler to update the done state
spanDone.onclick = updateDone;
// add the delete link
var spanDelete = document.createElement("span");
spanDelete.setAttribute("class", "delete");
spanDelete.innerHTML = " ✗ ";
// add the click handler to delete
spanDelete.onclick = deleteItem;
li.appendChild(spanDone);
li.appendChild(spanTodo);
li.appendChild(spanDelete);
return li;
}
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task"))
return;
var date = document.getElementById("dueDate").value;
if (checkInputText(date, "Please enter a due date")) return;
// later, process date here
//send date input to checkDate function, will validate correct format
//and return value for how many days until due or how many days overdue.
checkDate(date);
var numOfDays;
calculateDays(date);
var id = (new Date()).getTime();
//The findLocation function will call either the L14O2geolocation.js or
//the L14O2noGeolocation.js files, using the Modernizr.js file to check
//to see if geolocation is enabled, if so will display map where to do
//item is to be done and if not will return message no geolocation is
//enbled.
//var lat;
//var lon;
findLocation(lat, lon);
console.log("Return lat and long! " + lat + ", " + lon);
var todoItem = new Todo(id, task, who, date, lat, lon);
todos.push(todoItem);
addTodoToPage(todoItem);
saveToDoItem(todoItem);
// hide search results
hideSearchResults();
}
function checkInputText(value, msg) {
if (value == null || value == "") {
alert(msg);
return true;
}
return false;
}
//Move this function to the L14O2localStorage.js and
//14O2noLocalStorage.js files.
//function saveTodoItem(todoItem) {
// if (localStorage) {
// var key = "todo" + todoItem.id;
// var item = JSON.stringify(todoItem);
// localStorage.setItem(key, item);
// }
// else {
// console.log("Error: you don't have localStorage!");
// }
//}
function updateDone(e) {
var span = e.target;
var id = span.parentElement.id;
var item;
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) {
item = todos[i];
break;
}
}
if (item.done == false) {
item.done = true;
span.setAttribute("class", "done");
span.innerHTML = " ✔ ";
}
else if (item.done == true) {
item.done = false;
span.setAttribute("class", "notDone");
span.innerHTML = " ";
}
var itemJson = JSON.stringify(item);
var key = "todo" + id;
localStorage.setItem(key, itemJson);
}
function deleteItem(e) {
var span = e.target;
var id = span.parentElement.id;
// find and remove the item in localStorage
var key = "todo" + id;
localStorage.removeItem(key);
// find and remove the item in the array
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) {
todos.splice(i, 1);
break;
}
}
// find and remove the item in the page
var li = e.target.parentElement;
var ul = document.getElementById("todoList");
ul.removeChild(li);
//clear map from page
var map = document.getElementById("map");
map.innerHTML = "";
// hide search results
hideSearchResults();
}
// Search
function searchTodos() {
// new search, so clear previous results
clearSearchResultsList();
// get the text to search for
var searchTerm = document.getElementById("searchTerm").value;
var count = 0;
// check all the todos in the list
for (var i = 0; i < todos.length; i++) {
var todoItem = todos[i];
// make a regular expression to match the search term, regardless of
//case
var re = new RegExp(searchTerm, "i");
// try matching the expression with the task and the who from the to
//do item
if (todoItem.task.match(re) || todoItem.who.match(re)) {
// if we find a match, add the to do item to the search results
addSearchResultToPage(todoItem);
// keep a count of the number of items we match
count++;
}
}
// if we don't match any items, display "no results"
if (count == 0) {
var ul = document.getElementById("searchResultsList");
var li = document.createElement("li");
li.innerHTML = "No results!";
ul.appendChild(li);
}
// show the search results
showSearchResults();
}
// add a search result to the search results list in the page
function addSearchResultToPage(todoItem) {
var ul = document.getElementById("searchResultsList");
var li = document.createElement("li");
li.innerHTML =
todoItem.who + " needs to " + todoItem.task + " by " +
todoItem.dueDate;
ul.appendChild(li);
}
// clear the previous search results
function clearSearchResultsList() {
var ul = document.getElementById("searchResultsList");
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
}
function hideSearchResults() {
var div = document.getElementById("searchResults");
div.style.display = "none";
clearSearchResultsList();
}
function showSearchResults() {
var div = document.getElementById("searchResults");
div.style.display = "block";
document.forms[0].reset();
}
function checkDate(date) {
if (isValidDate(date) == false) {
return false;
}
console.log(date + " is a valid date");
return true;
}
function isValidDate(date) {
// Checks for the following valid date format of mm/dd/yyyy
// mm/dd/yyyy and yyyy/mm/dd
var regEx1 = /^(\d{2,2})(\/)(\d{2,2})\2(\d{4}|\d{4})$/;
// var regEx2 = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
//if (date != "" && date.match(regEx1) && date.match(regEx2) )
if (date != "" && date.match(regEx1)) {
alert("Invalid Date Format: " + date);
return false;
}
return true;
}
//Function to calculate the number of days until an item is either due
//or overdue.
function calculateDays(date) {
var today = new Date();
var d1 = today.getTime();
var dateIn = new Date(date);
var d2 = dateIn.getTime();
var year = today.getFullYear();
var month = today.getMonth()+1;
var day = today.getDate();
var time = today.getTime();
var total = parseInt((d1-d2)/(24*3600*1000));
console.log("Total: " + total);
return total;
}
The geolocation JavaScript File:
//If geolocation is found by Modernizr the map where the to do item is
//to be completed will be displayed in the mapDiv on the page.
function findLocation(lat, lon) {
console.log("In Geolocation");
navigator.geolocation.getCurrentPosition(displayLocation);
}
function displayLocation(position) {
var map = null;
latitude = position.coords.latitude;
longitude = position.coords.longitude;
lat = latitude;
lon = longitude;
console.log("Lat: " + lat + " Lon: " + lon);
if (!map) {
showMap(latitude, longitude);
}
addMarker(latitude, longitude);
return(lat, lon);
}
function showMap(lat, long) {
var googleLatLong = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 12,
center: googleLatLong,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
map.panTo(googleLatLong);
}
function addMarker(lat, long) {
var googleLatLong = new google.maps.LatLng(lat, long);
var markerOptions = {
position: googleLatLong,
map: map,
title: "Task Location"
}
var marker = new google.maps.Marker(markerOptions);
}
noGeolocation JavaScript File:
//If geolocation is not found by Modernizr a message will be displayed
//in the console and on the page showing that geolocation is not enabled.
function findLocation() {
var mapDiv = document.getElementById("map");
mapDiv.innerHTML = "Geolocation is not enabled on this browser.";
console.log("Geolocation is not enabled on this browser.");
}
localStorage JavaScript File:
//If localStorage is found by Modernizr the to do item will be stored in
//localStorage and message displayed in the console.
function saveToDoItem(todoItem) {
var key = "todo" + todoItem.id;
var item = JSON.stringify(todoItem);
localStorage.setItem(key, item);
console.log("Item: " + key + ", " + item + " stored in local storage");
}
noLocalStorage JavaScript File:
//If localStorage is found by Modernizr the to do item will be stored in
//localStorage and message displayed in the console.
function saveToDoItem(todoItem) {
var key = "todo" + todoItem.id;
var item = JSON.stringify(todoItem);
localStorage.setItem(key, item);
console.log("Item: " + key + ", " + item + " stored in local storage");
}

First, you need to remove the code for findlocation() from your toDo JavaScript file. Call the findlocation() in the getFormData function.
Your createNewTodo() code should start with:
function createNewTodo(todoItem) {
var li = document.createElement("li");
li.setAttribute("id", todoItem.id);
var spanTodo = document.createElement("span");
var daysUntilDue = calcDaysLeft(todoItem.dueDate);
spanTodo.innerHTML = CallTodoStr(todoItem, daysUntilDue);
}
Finally, you should have a code like this in your find Geolocation file:
function CallTodoStr(todoItem, daysUntilDue) {
var todoStr = "(" + todoItem.latitude + ", " + todoItem.longitude
+ ") " + todoItem.who + " needs to " + todoItem.task
+ " by " + todoItem.dueDate + " " + daysUntilDue;
return todoStr;
}

Related

i can't show span in function - javascript

i don't know how i can used if inside function then show it by span in html.
this my function:
<script type="text/javascript" src="praytimes.js"></script>
<script type="text/javascript">
function ptt() {
var date = new Date(); // today
var dhours = new Date().toTimeString().split(" ")[0];
var PT = new PrayTimes('Makkah');
var times = PT.getTimes(date, [24.46666, 39.59998], +3);
if (times.fajr > dhours){
document.getElementById("pyr").innerHTML = '<center>الفجر <br/>'+ times.fajr + '</center>';
} else if (times.sunrise > dhours){
document.getElementById("pyr").innerHTML = '<center>الإشراق <br/>'+ times.sunrise + '</center>';
} else if (times.dhuhr > dhours){
document.getElementById("pyr").innerHTML = '<center>الظهر <br/>'+ times.dhuhr + '</center>';
} else if (times.asr > dhours){
document.getElementById("pyr").innerHTML = '<center>العصر <br/>'+ times.asr + '</center>';
} else if (times.maghrib > dhours){
document.getElementById("pyr").innerHTML = '<center>المغرب <br/>'+ times.maghrib + '</center>';
} else if (times.isha > dhours){
document.getElementById('pyr').innerHTML+='<center>العشاء <br/>'+ times.isha + '</center>';
} else if (times.midnight > dhours){
//document.write('<br/>العشاء = '+ times.midnight);
document.getElementById('pyr').innerHTML+='<center>منتصف الليل '+ times.midnight + '</center>';
}
}
setTimeout('ptt()',1000);
</script>
and this tag in html:
<span id='pyr'></span>
but i can't show the result in html.
You can access a specific HTML element using the getElementById() method.
In your case the span's ID is pyr:
document.getElementById("pyr");
Now simply replace document.write() by document.getElementById("pyr").innerHTML+="your content here";
For example:
document.write('<br/>fa = '+ times.fajr);
becomes
document.getElementById("pyr").innerHTML+="<br/>fa = "+ times.fajr;
I don't think you call the function, at least not in the code you provided. Try to give your function a name and then call it.
function funcName () { ... }
funcname()
please i added new code to read lat and lng from gps:
navigator.geolocation.getCurrentPosition(function (pos) {
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
if (lat == null) {
var lat = 24.46666;
var lng = 39.59998;
} else {
alert("Latitude: "+ lat + " , Longitude: " + lng );
}
});
var date = new Date(); // today
var dhours = new Date().toTimeString().split(" ")[0];
var PT = new PrayTimes('Makkah');
var times = PT.getTimes(date, [lat, lng], +3);
but this line:
var times = PT.getTimes(date, [lat, lng], +3);
can't read lat and lng from this lines:
if (lat == null) {
var lat = 24.46666;
var lng = 39.59998;
please what is the wronge?

Undefined Value When Converting Metrics

One of my recent projects is to successfully get the temperature to convert from Fahrenheit to Celsius. However, I have run into a problem that gives me an undefined value when I click my button. Should I be referring to the temperature value that I have requested from my API? I believe that my conversion within my weather function isn't running when I call it.
Here's my codepen.
https://codepen.io/baquino1994/pen/qXjXOM?editors=0010
HTML
<span id="temp"></span>
<button id="tempunit">F</button>
JS
function weather(){
function success(position){
var latitude = position.coords.latitude;
var longitude= position.coords.longitude;
// location.innerHTML = "Latitude:" + latitude+"°"+ "Longitude: " + longitude+'°';
var theUrl = url +apiKey + "/"+ latitude+","+ longitude +"?callback=?";
$.getJSON(theUrl, function(data){
$("#temp").html(data.currently.temperature)
$("#minutely").html(data.minutely.summary)
// currentTempInFahrenheit = Math.round(data.html.currently.temperature * 10) /
$("#tempunit").text(tempUnit);
$.ajax({
url:'https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyBpiTf5uzEtJsKXReoOKXYw4RO0ayT2Opc', dataType: 'json',
success: function(results){
$("#city").text(results.results[3].address_components[4].long_name)
$("#country").text(results.results[0].address_components[5].long_name)
}
}
)}
);
}
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
navigator.geolocation.getCurrentPosition(success);
// location.innerHTML = "Locating...";
}
$(document).ready(function(){
weather();
});
var tempUnit = "F";
var currentTempInFahrenheit;
$("#tempunit").click(function(){
var currentTempUnit = $("#tempunit").text();
var newTempUnit = currentTempUnit == "F" ? "C" : "F";
$('#tempunit').text(newTempUnit);
if(newTempUnit == "F"){
var celTemp = Math.round(parseInt($('#temp').text())*5/9 - 32);
$("#temp").text(celTemp + " " + String.fromCharcode(176));
}
else{
$("#temp").text(currentTempInFahrenheit + " " + String.fromCharCode(176));
}
})
try this, my browser blocked geolocation, when i mocked the location i was able to get the codepen to work.
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
// navigator.geolocation.getCurrentPosition(success);
var position = { coords: { latitude: 32, longitude: -96 } };
success(position);

SpreadsheetApp.openById not going through in Google Spreadsheet

I am trying to run the function "onReportOrApprovalSubmit()" when I click on the message box that pops up when I open my google spreadsheet. The function runs perfectly fine when I run it in the script editor. However, when I try to run it using the message box that pops up when I first open the spreadsheet, the function stops running/gets stuck just before the line:
"var approvalsSpreadsheet = SpreadsheetApp.openById(APPROVALS_SPREADSHEET_ID);"
Does anyone have any idea why this is happening?
var APPROVALS_SPREADSHEET_ID = "1NC6mBPRXKCA4Blbn7C9lFt9YnTZioS3_vidbVuPvZos";
var APPROVAL_FORM_URL = "https://docs.google.com/a/londonhydro.com/forms/d/1BKuKdNwsUDXyLdqy18GAcQmE_SzS7Sq_OTxVNwyCH44/viewform";
var STATE_MANAGER_EMAIL = "MANAGER_EMAIL";
var STATE_APPROVED = "APPROVED";
var STATE_DENIED = "DENIED";
var COLUMN_STATE = 6;
var COLUMN_COMMENT = 7;
function onReportOrApprovalSubmit() {
// This is the Expense Report Spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Also open the Approvals Spreadsheet
var ui = SpreadsheetApp.getUi(); // DEBUG
ui.alert("heelo"); // DEBUG
var approvalsSpreadsheet = SpreadsheetApp.openById(APPROVALS_SPREADSHEET_ID);
var ui = SpreadsheetApp.getUi(); // DEBUG
ui.alert('Requests sentsee'); // DEBUG
var approvalsSheet = approvalsSpreadsheet.getSheets()[0];
// Fetch all the data from the Expense Report Spreadsheet
// getRowsData was reused from Reading Spreadsheet Data using JavaScript Objects tutorial
var data = getRowsData(sheet);
// Fetch all the data from the Approvals Spreadsheet
var approvalsData = getApprovalData(approvalsSheet);
// For every expense report
for (var i = 0; i < data.length; i++) {
var row = data[i];
row.rowNumber = i + 2;
Logger.log("Row num: " + row.rowNumber);
Logger.log("row state before: " + row.state);
Logger.log("row email before: " + row.emailAddress);
if (!row.state) {
Logger.log("row state: " + row.state);
sendReportToManager(row);
sheet.getRange(row.rowNumber, COLUMN_STATE).setValue(row.state);
Logger.log("row state: " + row.state);
} else if (row.state == STATE_MANAGER_EMAIL) {
for (var j = 0; j < approvalsData.length; ++j) {
var approval = approvalsData[j];
if (row.rowNumber != approval.expenseReportId) {
Logger.log("failed expenseId: " + approval.expenseReportId + " rowNumber: " + row.rowNumber);
continue;
}
Logger.log("pass");
// Email the employee to notify the Manager's decision about the expense report.
sendApprovalResults(row, approval);
// Update the state of the report to APPROVED or DENIED
sheet.getRange(row.rowNumber, COLUMN_STATE).setValue(row.state);
break;
}
}
}
}
Row = function(){
};
function getRowsData(sheet){
var data = sheet.getDataRange().getValues();
var row = new Row();
var rows = [];
var counter = 0;
for (var i = 0; i < data.length; i++) {
row = new Row();
row.time = data[i][0];
row.emailAddress = data[i][1];
row.amount = data[i][2];
row.description = data[i][3];
row.managersEmailAddress = data[i][4];
row.state = data[i][5];
if(i != 0){
Logger.log("row state1: " + row.state);
rows[counter] = row;
counter++;
}
}
Logger.log("rowsss:");
Logger.log(rows);
Logger.log("data length: " + rows.length);
Logger.log("data display: ");
for(var k = 0; k < rows.length; k++){
Logger.log(rows[k].state);
}
return rows;
}
ApprovalData = function(){
};
function getApprovalData(sheet){
var data = sheet.getDataRange().getValues();
var row = new ApprovalData();
var rows = [];
for (var i = 0; i < data.length; i++) {
row.time = data[i][0];
row.emailAddress = data[i][1];
row.expenseReportId = data[i][2];
row.approveExpenseReport = data[i][3];
row.comments = data[i][4];
rows[i] = row;
}
return rows;
}
// Sends an email to an employee to communicate the manager's decision on a given Expense Report.
function sendApprovalResults(row, approval) {
var approvedOrRejected = (approval.approveExpenseReport == "Yes") ? "approved" : "rejected";
var message = "<HTML><BODY>"
+ "<P>" + approval.emailAddress + " has " + approvedOrRejected + " your expense report."
+ "<P>Amount: $" + row.amount
+ "<P>Description: " + row.description
+ "<P>Report Id: " + row.rowNumber
+ "<P>Manager's comment: " + (approval.comments || "")
+ "</HTML></BODY>";
MailApp.sendEmail(row.emailAddress, "Expense Report Approval Results", "", {htmlBody: message});
if (approval.approveExpenseReport == "Yes") {
row.state = STATE_APPROVED;
} else {
row.state = STATE_DENIED;
}
}
// Sends an email to a manager to request his approval of an employee expense report.
function sendReportToManager(row) {
var message = "<HTML><BODY>"
+ "<P>" + row.emailAddress + " has requested your approval for an expense report."
+ "<P>" + "Amount: $" + row.amount
+ "<P>" + "Description: " + row.description
+ "<P>" + "Report Id: " + row.rowNumber
+ '<P>Please approve or reject the expense report here.'
+ "</HTML></BODY>";
MailApp.sendEmail(row.managersEmailAddress, "Expense Report Approval Request", "", {htmlBody: message});
row.state = STATE_MANAGER_EMAIL;
Logger.log("id: " + row.rowNumber);
}
function onOpen() {
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert(
'Do you want to get new requests?',
ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.YES) {
// User clicked "Yes".
onReportOrApprovalSubmit();
ui.alert('Requests sent');
} else {
// User clicked "No" or X in the title bar.
ui.alert('No requests sent');
}
}
The function onOpen can only access the spreadsheet it is bound to, not others. The UI prompt doesn't change that: showing a custom dialog doesn't add any authorization to the function. One cannot access other spreadsheets from a process that is launched by a simple trigger, such as onOpen.
Solution: let onOpen add menu items that will be used to launch any functions requiring authorization.
function onOpen() {
var menu = [{name: "Get New Requests", functionName: "onReportOrApprovalSubmit"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("Script", menu);
}

Excel VBA (via JavaScript) - Moving a Sheet to a new location

With the following code, I am attempting to move a Sheet in my Excel workbook from one location to another. However, instead of making the move - Excel creates a new Workbook. How do I move a Sheet from one location to another within the same Workbook?
///////////////////////////////////////////////////////////////////////////
// //
// function serviceInitExcel($scope) //
// Version: //
// Description: Initialize Excel Spreadsheet //
// Date: //
// To Do: //
// Author: //
// //
///////////////////////////////////////////////////////////////////////////
var serviceInitExcel = function() {
var _SCFR;
var _filename = "emptyServiceValue";
var _serviceBrowser = "";
var service = {};
service.soundOff = function() {
alert("Another generic method");
}
service.initExcel = function() {
var _scfr = new ActiveXObject("Excel.Application");
_scfr.Visible = true;
_scfr.Workbooks.Add;
// alert("Application Initialized: " + _scfr.Name);
_SCFR = _scfr;
return _SCFR;
} // genericMethod
service.createSheet = function(iWorkbook, sheetName) {
var pblSheet = iWorkbook.Sheets("Payable");
pblSheet.Range("A1").Value = "Payable Sheet";
var newSheet = iWorkbook.Worksheets.Add;
newSheet.Name = sheetName;
newSheet.Select
newSheet.Range("A1").Value = "_SCFR.Name: " + _SCFR.Name;
newSheet.Range("A2").Value = "ActiveWorkbook: " + _SCFR.ActiveWorkbook.Name;
newSheet.Range("A3").Value = "Sheet 1: " + _SCFR.ActiveWorkbook.Sheets(1).Name;
newSheet.Range("A4").Value = "Sheet 2: " + _SCFR.ActiveWorkbook.Sheets(2).Name;
newSheet.Range("A5").Value = "Sheet 3: " + _SCFR.ActiveWorkbook.Sheets(3).Name;
newSheet.Range("A6").Value = "testSheet: " + iWorkbook.Sheets("testSheet").Name;
newSheet.Range("A7").Value = "Payable: " + iWorkbook.Sheets("Payable").Name;
newSheet.Range("A8").Value = "Paid: " + iWorkbook.Sheets("Paid").Name;
for (var s=0; s < 500; s++) {
newSheet.Range("A9").Value = s;
newSheet.Select
iWorkbook.Sheets("Payable").Select
}
iWorkbook.Sheets(newSheet.Name).Move + "After:=" + iWorkbook.Sheets("Payable");
// newSheet.Move + "After:=" + iWorkbook.Sheets(3);
// Sheets("Payable").Select
// Sheets.Add
// Sheets("Sheet6").Select
// Sheets("Sheet6").Move After:=Sheets(3)
// _SCFR.Workbooks("Book1.xlsx").Sheets("testSheet").Move + "After:=" + _SCFR.Workbooks("Book1.xlsx").Sheets("Payable");
return iWorkbook;
} // genericMethod
return service;
}
This should do it:
newSheet.Move(null, iWorkbook.Sheets("Payable"))
I think if you take out the concatenation it will work fine. Try this:
iWorkbook.Sheets(newSheet.Name).Move After:=iWorkbook.Sheets("Payable")

Why markers do not move correcly on map

Sample of JSON data (from the comments):
[{"id":"280","id_vehicle":"VL0847810531","lat":"30.0761","longi":"1.01981","spee‌​d":"144","time":"2014-12-03 12:07:23"},{"id":"202","id_vehicle":"VL0645210631","lat":"34.7344","longi":"7.32‌​019","speed":"78","time":"2014-12-03 11:55:44"}]
function updateLocations(jsonData)
{
for (i=0 ;i< jsonData.length; i++) //for all vehicles
{
var id_vehicle = jsonData[i]["id_vehicle"];
var lat = jsonData[i]["lat"];
var lng = jsonData[i]["longi"];
var speed = jsonData[i]["speed"];
var str_time = jsonData[i]["time"];
/************************update list*******************************/
var state_icon, marker_icon, state;
var time = moment(str_time);
var last_10_Min = moment().subtract({minutes: 60 + 10});
if(time.isBefore(last_10_Min)) //if before 10 last minutes
{
state_icon = INACTIVE_IMG;
marker_icon = INACTIVE_VEHICLE;
state = "INACTIVE";
}
else //if befor
{
if(jsonData[i]["speed"] > 10) //if > 2 km/h then running
{
state_icon = RUN_IMG;
marker_icon = RUN_VEHICLE;
state = "RUN";
}
else
{
state_icon = STOP_IMG;
marker_icon = STOP_VEHICLE;
state = "STOP";
}
}
$("#state_img_"+id_vehicle).attr("src", state_icon);
$("#state_img_"+id_vehicle).attr('state',state);
$("#select_"+id_vehicle).attr("disabled" , false ); // enable selection
/************************update location info*******************************/
var locationInfo = new Array();
img = "<img src=" + state_icon + " width='16' height='16' >";
locationInfo.push("Etat : " + state + " " + img + "<br>");
locationInfo.push("Latitude : " + lat + "<br>");
locationInfo.push("Longitude : " + lng + "<br>");
locationInfo.push("Vitess: " + speed + " klm/h<br>");
locationInfo.push("Temps : " + str_time + "<br>");
$("#info_location_" +id_vehicle).html(locationInfo.join(""));
/*****************update vehicles on map *************/
try {
cBox = $("#select_"+id_vehicle);
if(cBox.is(':checked')) //update selected only
{
//get marker index
var id_map = cBox.attr("id_map");
//change title
title = "Latitude: "+ lat + "\nLongitude: " + lng + "\nSpeed: " + speed + "\nTime: " + str_time;
arrayMarker[id_map].setTitle(title); //update title
arrayMarker[id_map].setIcon(marker_icon);
//move marker
arrayMarker[id_map].setPosition( new google.maps.LatLng(parseFloat(lat),parseFloat(lng)) );
}
}catch(error){};
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
my question is why whene this function is executed (updating locations) just fisrt vehicle on map is moved correctly, the ohers are updated (title, icon ...) but do not move?
I noticed that , they move and return to their old location quickly.
Thanks for any suggestion.
finaly i found problem, it was here:
var marker = new MarkerWithLabel({......});
arrayMarker[id_map] = marker; //put marker in arrayMarker at indexMarker position
the bug occur whene i filled my arrayMarker using MarkerWithLabel (3th lib)
whene changed to native google.maps.Marker it work correcly:
var marker = new google.maps.Marker({......});
arrayMarker[id_map] = marker;

Categories

Resources