GoogleApp script. Google calendar script that display current day events - javascript

I have some questions regarding google calendar script that I'm building. So I managed to write the script and deploy it as a web app, but I encountered some problems:
1) It should list all current day events, but it lists only one event of the day
2) Also I want to display only the title of the event (it’s working now) and the start time and end time of the event. I managed to display a title (events[i].summary) and the start time of the event, but I was unable to display end time of the event and to change the format of the time that it would display time like this for example : 1pm – 2 pm.
3) Also what I want to do is to make the script run without pressing a button. I want it to work every time I open the published web app or refresh the web app page.
Here is the script code:
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp');
}
function listEvents() {
var actualDate = new Date();
var endOfDayDate = new
Date(actualDate.getFullYear(),actualDate.getMonth(),actualDate.getDate(),23,59,59);
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
timeMax: endOfDayDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};
var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;
var allEvents = [];
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
allEvents.push(events[i].summary + ' ' + events[i].start.dateTime);
}
return allEvents;
} else {
return ['No events found'];
}
And this is a HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Calendar App</h1>
<button onclick="listEvents()">List events</button>
<ul id='events'></ul>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(response){
var events = response;
for(var i = 0; i < events.length; i++) {
document.getElementById('events').innerHTML = '<li>' + response[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
</script>
</body>
</html>
This is the link to actual google scritp: Google Script
Thank you in advance for your help :)

Here is your modified (and working) code. You don't need to use advanced Calendar API since everything you need is available in CalendarApp, including a convenient getEventsForDay().
It shows all your events on opening as required.
code :
function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp').setTitle('CalendarApp');
}
function listEvents() {
var today = new Date();
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEventsForDay(today);
var data = [];
data.push("Events for today "+Utilities.formatDate(today,Session.getScriptTimeZone(),"MMM dd yyyy"));
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
data.push(events[i].getTitle()+' : '+Utilities.formatDate(events[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm")+' - '+Utilities.formatDate(events[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
}
return data;
} else {
return ['No events found','',''];
}
}
html & script :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style="font-family:arial,sans;font-size:12pt">
<h2>Calendar App</h2>
<div id="events">
</div>
<script>
function listEvents() {
google.script.run
.withSuccessHandler(function(events){
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<p>' + events[0] + '</p>';
for(var i = 1; i < events.length; i++) {
document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<li>' + events[i] + '</li>';
}
})
.withFailureHandler(function(err){
console.log(err);
})
.listEvents();
};
window.onload = listEvents();
</script>
</body>
</html>

Here's a function I use to get my calendar events for the next 5 weeks. And I use it in conjunction with a webapp so it gets returned to a statement that looks like this document.getElementById('hotbox').innerHTML=hl; hotbox is just a div.
function getMyEvents()
{
var allCals=CalendarApp.getAllCalendars();
var s=Utilities.formatString('<strong>%s</strong>',Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM d, yyyy HHmm"))
var min=60 * 1000;
var hr=60 * min;
var day=24 * hr;
var wk=7 * day;
var start = new Date(new Date().setHours(0,0,0));
var end=new Date(start.valueOf() + (5 * wk));//you could make this + day instead of + (5 * wk)
var incl=['Calendar1Name','Calendar2Name'];//These are different calendar names as I have some special calendars for different functions
for(var i=0;i<allCals.length;i++)
{
if(incl.indexOf(allCals[i].getName())>-1)
{
s+=Utilities.formatString('<br /><strong>%s</strong>',allCals[i].getName());
var events=allCals[i].getEvents(start, end);
if(events)
{
s+='<br><ul>';
for(j=0;j<events.length;j++)
{
var calId=allCals[i].getId();
var evId=events[j].getId();
if(events[j].isAllDayEvent())
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s %s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),'All Day',Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d"),calId,evId);
}
else
{
s+=Utilities.formatString('<li><strong>%s</strong>-%s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d, HHmm"),calId,evId);
}
}
s+='</ul>';
}
}
}
s+='<br /><input type="button" value="Delete Selected Events" onClick="delSelectedEvents();" style="width:250px;height:35px;text-align:center;margin:10px 0 10px 0;" />';
//var ui=HtmlService.createHtmlOutput(s);
//SpreadsheetApp.getUi().showModelessDialog(ui, 'My Events');
return s;
}

Related

Chrome Extension: calculate in miliseconds and click button after specific seconds

Well i am practising on Chrome Extension , i'm newbie on this.
Here is my code.
popup.html
<!doctype html>
<html>
<head>
<title>Laser Script</title>
<script type="text/javascript" src="popup.js"></script>
<style type="text/css">
h1 { font-size: 22px; }
.powered {
font-size: 14px;
margin-top: 8px;
}
</style>
</head>
<body>
<h1>Scheduled Click</h1>
<div id="contentWrapper">
<input type="text" id="duration" placeholder="Duration">
<input type="text" id="attack_date" placeholder="Day/Month/Year">
<input type="text" id="attack_time" placeholder="00:00:00">
<button id="schedule">Start Attack</button>
</div>
<div class="powered">Courtesy of <img src="justpark_logo.png" width="170px"></div>
</body>
</html>
popup.js
function initialise () {
// here im calculating the remind time in (mileseconds) that the button have to be pressed
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds, mileseconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
function scheduleClick () {
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
var codeString = 'var button = document.getElementById("troop_confirm_go"); setTimeout( function() { button.click(); },' + delayInputValue + ' )';
console.log(codeString);
chrome.tabs.executeScript({ code: 'console.log(document.getElementById("The attack will start ' + delayInputValue + ' miliseconds"))' });
chrome.tabs.executeScript({ code: codeString});
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
So i have 3 inputs. I calculate the remind time until the button will be clicked. (it works)
But in this part
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
it diplays
The attack will start in NaN miliseconds.
and the button is pressed instantly.
I ckeched also this code:
var p = 1 ; //it's outside the function as the var delayInputValue
document.getElementById("contentWrapper").innerHTML = 'The attack will start in ' + delayInputValue + 'seconds';
and it displays :
The attack will start in 1 miliseconds.
So here is my question, why it can't read and work with the var delayInputValue but i can the var p?
Can i fix it somehow ?
Got it - the initialise() function is called when your DOM content is finished loading. At that point, the user has not entered information into the text fields, so they show as null or undefined. When the code starts running with this data it produces data as NaN since the calculations don't work.
In order for the code to run properly, you need to place the code dealing with data from those fields inside the scheduleClick() function, like so:
function initialise () {
function scheduleClick () {
var attack_timeInput = document.getElementById("attack_time");
var attack_timeParts = attack_timeInput.value.split(":");
var hours = parseInt(attack_timeParts[0],10);
var minutes = parseInt(attack_timeParts[1],10);
var seconds = parseInt(attack_timeParts[2],10);
//var mileseconds = parseInt(attack_timeParts[3],10);
var attack_DateInput = document.getElementById("attack_date");
var attack_DateInputParts = attack_DateInput.value.split("/");
var day = parseInt(attack_DateInputParts[0],10);
var month = parseInt(attack_DateInputParts[1],10);
var year = parseInt(attack_DateInputParts[2],10);
var durationInput = document.getElementById("duration");
var durationParts = durationInput.value.split(":");
var hours2 = parseInt(durationParts[0],10)*3600000;
var minutes2 = parseInt(durationParts[1],10)*60000;
var seconds2 = parseInt(durationParts[2],10)*1000;
var duration_mile = hours2+minutes2+seconds2;
var now = new Date();
var new_now = now.getTime();
var full_attack_date = new Date(year, month-1, day, hours, minutes, seconds);
var new_full_attack_date = full_attack_date.getTime();
var delayInputValue = new_full_attack_date - new_now - duration_mile;
document.getElementsByTagName("div")[0].innerHTML = 'The attack will start in ' + delayInputValue + 'miliseconds';
};
scheduleButton = document.getElementById("schedule");
scheduleButton.addEventListener('click', scheduleClick, true);
};
document.addEventListener('DOMContentLoaded', initialise, false);
Note that I also removed the miliseconds variable as the inputs I was using included hours, minutes and seconds only. You should also add some code to sanitise inputs to make sure they are in the format you want before calling the function.
Hope that helps

Unable to call JavaScript method based on button element "id"

I am following a tutorial from Head First Javascript. In the tutorial, the showBlogs() method is called via the following html code
HTML button
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
function showBlogs(numberOfEntries){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
However, when I create another button and access it via javascript and call the same method with the event handler - nothing happens.
Button
<button type="button" id="showAllBlogs">Show All Posts</button>
Access Button within Javascript
const showBlogsButton = document.getElementById('showAllBlogs');
Call the showBlogs method
showBlogsButton.addEventListener('click', showBlogs);
I did try creating another function say 'foo()' and I called foo() with the new button and I was able to invoke the method. But when I call the showBlogs() method, nothing happens.
JAVASCRIPT CODE
`
//dom elements
const blogsDOM = document.getElementById('blog');
const query = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const showBlogsButton = document.getElementById('showAllBlogs');
// Constructor
function Blog(body, dateString){
this.body = body;
this.date = new Date(dateString);
this.toString = function(){
return this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body;
};
this.toHTML = function(highlight){
var htmlPost = "";
//determine to highlight post
htmlPost += highlight ? "<p style='background-color: #EEEEEE'>" : "<p>";
//generate formatted html
htmlPost += this.date.getMonth() + '/' + this.date.getDate() + '/' + this.date.getFullYear() + '/' +
this.body + "</p>";
//return html
return htmlPost;
};
this.containsText = function(text){
return this.body.toLowerCase().indexOf(text.toLowerCase()) > -1;
};
}
//Array of blogs
var blogs = [
new Blog("Got the new cube I ordered", "01/25/1986"),
new Blog("This new cube works just fine", "02/22/2000"),
new Blog("This is going to be the third one", "03/23/2005"),
new Blog("This is the final one", "03/21/2020")
]
blogs.sort(function(blog1, blog2){ return blog2.date - blog1.date; })
function getDaysBetweenDates(date1, date2){
var daysBetween = (date2 - date1) / (1000 * 60 * 60 * 24);
return Math.round(daysBetween);
}
function formatDate(date){
return date.getDay() + '/' + date.getMonth() + '/' + date.getYear();
}
function searchForPost(event){
let matchingBlogs = [];
event.preventDefault();
const searchQuery = query.value;
blogs.forEach(blog =>{
if(blog.body.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1){
matchingBlogs.push(blog);
}
} )
showBlogs(matchingBlogs.length, matchingBlogs);
}
//show list of blog
function showBlogs(numberOfEntries, blogsToShow = blogs){
//sort the blogs in reverse chronological order (most recent first)
blogs.sort(function(blog1, blog2){
return blog2.date - blog1.date;
})
//set the number of entires if non specified
if(!numberOfEntries){
numberOfEntries = blogs.length;
}
//set blog entries
var currenetBlog = 0; blogListHTML = "";
while(currenetBlog < blogs.length && currenetBlog < numberOfEntries){
blogListHTML += blogs[currenetBlog].toHTML(currenetBlog % 2 == 0);
currenetBlog++;
}
//display blog entries
blogsDOM.innerHTML = blogListHTML;
}
searchButton.addEventListener('click', searchForPost);
showBlogsButton.addEventListener('click', showBlogs);`
HTML CODE
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blog</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Youtube - the Blog for Cube puzzlers</h3>
<div class="search-container">
<input type="text" id="searchInput" placeholder="Search for a blog"/>
<button type="button" id="searchButton">Search the blog</button>
</div>
<div id="blog"></div>
<input type="button" id="showall" value="Show all blog entries" onclick="showBlogs();" />
<button type="button" id="showAllBlogs">Show All Posts</button>
<script src="script.js"></script>
</body>
</html>`

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Fetch data from excel sheet using Javascript

I am using following code to extract data from excel sheet using javascript. This is working good and after opening the HTML page, getting the data that I want and closing the page, I am unable to open and edit the excel sheet as it is throwing the exception, "File already held by the user and unable to be edited". Is there anyway to handle the closing of excel sheet at the end of the code? Please help me.
<!DOCTYPE html>
<html>
<body>
Enter Salomon account:<br>
<input type="text" id="myText" name="SalAccount">
<br>
<button onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script language="javascript" >
function myFunction()
{
alert("hello");
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:/Users/bv15457/Desktop/test1.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var x = document.getElementById("myText").value;
var lo = 1;
var hi = 682220;
var mid;
var element;
var Flag = 0;
while(lo <= hi && Flag != 1)
{
mid = Math.floor((lo + hi) / 2, 10);
element = excel_sheet.Cells(mid,1).Value;
if (element < x)
{
lo = mid + 1;
}
else if (element > x)
{
hi = mid - 1;
}
else
{
document.getElementById("demo").innerHTML = excel_sheet.Cells(mid,2).Value;
Flag = 1;
}
}
if (Flag != 1)
{
alert("Account is not found in XREF file");
}
}
</script>
</body>
</html>

Categories

Resources