I'm trying to get that day - Javascript - javascript

I have a script that finds that day, date and year.
But two days it should say "I am closed" below the day...
those two days is 'Søndag' and 'Onsdag'
I have tried to make an if statement but it doesn't seem to work :(
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS - Testing</title>
</head>
<body>
<b id="calendar-day"></b> -
<b id="calendar-date"></b>
<b id="calendar-month-year"></b>
<p></p>
</body>
<script src="main.js"></script>
</html>
JS
//function that gets the day and date
function calendar() {
var day = ['Søndag', 'Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];
var month = ['Januar','Febuar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'];
var d = new Date();
setText('calendar-day', day[d.getDay()]);
setText('calendar-date', d.getDate());
setText('calendar-month-year', month[d.getMonth()]+' '+(1900+d.getYear()));
checkDay();
};
//function that sees if it's closing day
var paragraph = document.querySelector('p');
function checkDay() {
if (day == 'Onsdag') {
paragraph.innerText = 'I am closed';
}
}
function setText(id, val){
if(val < 10){
val = '0' + val; //add leading 0 if val < 10
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;

Probably You are trying to do this. You cant directly access day into checkDay function rather you need to pass it as a parameter and then. Secondly, You can't directly extract a value from day because it's an array not integer or string, so you need to loop through the array in order to find the right value
function calendar() {
var day = ['Søndag', 'Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];
var month = ['Januar','Febuar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'];
var d = new Date();
var today = day[d.getDay()];
setText('calendar-day', today);
setText('calendar-date', d.getDate());
setText('calendar-month-year', month[d.getMonth()]+' '+(1900+d.getYear()));
checkDay(today);
};
//function that sees if it's closing day
var paragraph = document.querySelector('p');
function checkDay(day) {
if (day == 'Onsdag' || day == 'Søndag') {
paragraph.innerText = 'I am closed';
} else paragraph.innerText = 'I am opened';
}
function setText(id, val){
if(val < 10){
val = '0' + val; //add leading 0 if val < 10
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS - Testing</title>
</head>
<body>
<b id="calendar-day"></b> -
<b id="calendar-date"></b>
<b id="calendar-month-year"></b>
<p></p>
</body>
<script src="main.js"></script>
</html>

The most prized quality in a developer is laziness. Don't be messing around in the reeds there :-) Use the Date object to manipulate dates, and, these days, there's really no excuse for not using Vue when you want to manipulate the DOM.
To get danish weekdays, use myDate.toLocaleDateString('da-DK',{weekday:'long'}). The same goes for month names. Docs are here.
To find out if a day is on the weekend, use (myDate.getDay() === 6) || (myDate.getDay() === 0);
Here's your example working, with 13 lines of script and 6 lines of markup.
var vm = new Vue({
el : "#vueRoot",
data : { myDate : new Date() },
computed : {
formattedDate(){
return this.myDate.toLocaleDateString(
'da-DK',
{weekday:'long', day:'numeric', month:'long', year:'numeric'}
);
},
isOpen(){return !(this.myDate.getDay() === 3 || this.myDate.getDay() === 0)}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vueRoot">
<b>{{formattedDate}}</b>
<br>
{{isOpen?'I am OPEN':'I am CLOSED'}}
</div>

I have passed day into checkDay:
//function that gets the day and date
function calendar() {
var day = ['Søndag', 'Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];
var month = ['Januar','Febuar','Marts','April','Maj','Juni','Juli','August','September','Oktober','November','December'];
var d = new Date();
setText('calendar-day', day[d.getDay()]);
desiredDay = day[d.getDay()];
setText('calendar-date', d.getDate());
setText('calendar-month-year', month[d.getMonth()]+' '+(1900+d.getYear()));
checkDay(desiredDay);
};
//function that sees if it's closing day
var paragraph = document.querySelector('p');
function checkDay(day) {
if (day == 'Onsdag') {
paragraph.innerText = 'I am closed';
}
}
function setText(id, val){
if(val < 10){
val = '0' + val; //add leading 0 if val < 10
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JS - Testing</title>
</head>
<body>
<b id="calendar-day"></b> -
<b id="calendar-date"></b>
<b id="calendar-month-year"></b>
<p></p>
</body>
<script src="main.js"></script>
</html>
day was undefined in the checkDay function

Related

How can i activate date, month and year in Air Datepicker (function onRenderCell)

I want to set up a calendar in such a way that it would show the years, months and dates in an array. I think this should work in the onRenderCell function but don't fully understand it.
In AirDatepicker, the days of the month, 12 months and a window of years are drawn separately. The numbers of the month are displayed correctly. Months and years are not displayed.
my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script>
</head>
<body>
<input type="text" id="datepicker">
<script src="main.js"></script>
</body>
</html>
my js
let days = [ "2022-4-15", "2022-5-3", "2022-4-1", "2021-2-20"];
$('#datepicker').datepicker({
onRenderCell: function (date, cellType) {
new_date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
//all dates passive
let disabled = true;
//if the date is in the array, she becomes active
if (cellType == 'day'){
disabled = days.indexOf(new_date) == -1
}
//called but not working
if (cellType == 'month' && disabled == false){
disabled = days.indexOf(new_date) == -1
}
if (cellType == 'year' && disabled == false){
disabled = days.indexOf(new_date) == -1
}
return {disabled: disabled}
}
});
Tell me what exactly am I doing wrong? How to make it so that when choosing months, those of them that have the desired dates are displayed?

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>`

Adjust HTML with javascript

I have a personal time keeper I am putting together for work. We are allotted 50 minutes a week, and I wanted to make a fancy way of keeping track of that time.
I have a method that works:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#example1 {
background-color="#0CD6C7";
}
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').value = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font face="arial">
<input id="time1" value="50:00" size="5"> 50 minutes of personal time per week <br>
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your personal break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1','time2',false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; }
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
Enter in the length of the break in the second input field and that time is subtracted from the total.
To make it look fancier, I want the total time to appear as only text, not as an input field.
This is what I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
I know I need to use innerHTML, but it's just not quite clicking. Any pointers in the right direction would be much appreciated!
Change the below line
var tt1 = document.getElementById(id1).value;
to
var p = document.getElementById(id1);
var tt1 = p.textContent;
This is because, value function is applicable only to input tags. For the other plain text tags like p, headings, etc. textContent should be fetched.
What wrong is since t1 is a p tag, it doesn't have value so tt1.split(':'); will throw an exception. Use innerText instead.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).innerText;
if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0;
if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>

GoogleApp script. Google calendar script that display current day events

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;
}

code to exclude weekends an bank holidays

I'm trying to write the code to get the "date" excluding weekends and bank holidays( which means when I enter the date and number of days, it should exclude weekends and bank holidays, like when I give 03-24-2017 and 3 days, it should give 03-31-2017 assuming 29th is a holiday). I got the code for whole thing, but it is taking todays date, but I wish to enter the date manually, I tried with document.getElementById("today").value; but its not giving any output.Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Add Days and Holidays </title>
</head>
<body>
<pre id="fourWeeks"></pre>
Add <input id="nDaysToAdd" value="0"> days<p>
<button onclick="calcBusinessDay()"> Calculate
</button>
<div id="debug"</div>
<script type="text/javascript">
var today = new Date();
var holidays = [
[2017,2,10],
before holiday
[2017,7,4],
];
Date.prototype.addDays = function (days) { return new
Date(this.getTime() + days*24*60*60*1000); }
Date.prototype.addBusAndHoliDays = function (days) {
var cDate = this;
var holiday = new Date();
var c='', h='';
for (var i=1; i<=days ; i++){
cDate.setDate(cDate.getDate() + 1);
if (cDate.getDay() == 6 || cDate.getDay() == 0) {
days++; }
else {
for (j=0; j<holidays.length; j++) {
holiday = new
Date(holidays[j][0],(holidays[j][1]-1),holidays[j][2]);
c = cDate.toDateString(); h =
holiday.toDateString();
if (c == h) { days++; }
}
}
} return cDate;
}
Date.prototype.DayList = function (daysToShow) {
var td = this;
if (daysToShow == undefined) { daysToShow = 31; }
var str = '';
for (var i=0; i<daysToShow; i++) {
newday = new
Date(td.getFullYear(),td.getMonth(),(td.getDate()+i));
str += newday.toDateString()+'\t =>\t'+i+' actual days
ahead<br>';
} return str;
}
function calcBusinessDay() {
functions
var today = new Date();
var N =
parseInt(document.getElementById('nDaysToAdd').valu
e) || 0;
var wd = today.addDays(N);
document.getElementById('debug').innerHTML
= '<p>'+N+' week days from today
('+today.toDateString() +') will be on:
'+wd.toDateString();
var bd = today.addBusAndHoliDays(N);
document.getElementById('debug').innerHTML +=
'<p>'+N+' business days will be on: '+bd.toDateString();
str += '<p>'+newDay.DayList(14);
document.getElementById('debug').innerHTML +=
'<p>'+str;
}
</script>
</body>
</html>
With document.getElementById("today").value you get the value of an INPUT html element, and you don't have any input with todays value.
Here's an snippet getting todays date (Warning: the date is formatted d/m/y)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.rawgit.com/JDMcKinstry/JavaScriptDateFormat/master/Date.format.min.js"></script>
</head>
<body>
Today: <input id="today" type="text">
<br>
<button onclick="calculate()" >Calculate something</button>
<div id="results" style="margin-top: 20px; border: red;"></div>
<script>
document.getElementById("today").value = new Date().format('d/m/Y');
function calculate() {
var splitted = document.getElementById("today").value.split("/");
var today = new Date(splitted[2], splitted[1] - 1, splitted[0]);
document.getElementById("results").innerHTML = "Today is " + today;
}
</script>
</body>
</html>

Categories

Resources