Javascript calendar won't show current day+month - javascript

I'm making a calendar in javascript, and i wan't to show the current day, dayname and monthname inside a <div id=taken> it is inside my function Kalender() but for some reason if i execute the function volgende() (Next Month) it changes the month in the <div id=taken> aswell which isn't the current day and month how can i fix this?
var dayNames = ['Zon', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
//Volledige Dagnamen//
var dayNamesFull = ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'];
//Volledige Maandnamen//
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'Oktober', 'November', 'December'];
//Maand lengte van 0 - 11//
var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];
//Nieuwe datum//
var today = new Date();
//Vandaag//
var day = today.getDay();
//vandaag zoekmaand//
var month = today.getMonth();
//vandaag//
var vandaag = today.getDate();
//volledig jaar//
var year = today.getFullYear();
//Kalender schrijf functie//
function Kalender() {
var buttons = '<button id="vorige" onclick="vorige()">Vorige</button><button id="volgende" onclick="volgende()">Volgende</button>'
var kalender = "";
document.getElementById('Header').innerHTML = monthNames[month]+" "+year+buttons;
kalender += '<table id="cal"><div id="taken"></div>';
for (var j = 1; j <= monthLength[month]; j++) {
if (vandaag == j ) {
kalender +="<td id='tabeldagen' class='dagVandaag'>"+j;
}
else {
kalender += "<td id='tabeldagen'>"+j;
}
if (j % 7 == 0) {
kalender += "<tr>";
}
kalender += '</td>';
}
kalender += '</table>';
document.getElementById('kalen').innerHTML = kalender;
document.getElementById('taken').innerHTML += dayNamesFull[day]+" "+vandaag+" "+monthNames[month];
}
//Leap Year//
if (month == 1) {
if (year % 4 == 0) {
monthLength = 29;
}
}
//Volgende Maand functie//
function volgende() {
month = month + 1;
if(month > 11) {
month = -1;
month = month + 1;
year = year + 1;
}
Kalender();
}
//Vorige maand functie//
function vorige() {
month = month - 1;
if(month < 0) {
month = + 12;
month = month - 1;
year = year - 1;
}
Kalender();
}
HTML:
<!DOCTYPE html>
<head>
<title>Kalender</title>
<link type="text/css" rel="stylesheet" href="kalender.css">
</head>
<body onload="Kalender()">
<div id="kalender">
<div id="Header">
</div>
<div id="kalen">
</div>
</div>
<script type="text/javascript" src="Kalender.js"></script>
</body>
</html>

The problem is that you change day and month variables in functions volgende() and vorige(). Try adding another variables for current day and month:
//Vandaag//
var day = today.getDay();
var currentDay = day;
//vandaag zoekmaand//
var month = today.getMonth();
var currentMonth= month;
and use them in taken element:
document.getElementById('taken').innerHTML += dayNamesFull[currentDay]+" "+vandaag+" "+monthNames[currentMonth];

Related

Time difference calculating program being slightly off

I'm fairly new to JS and making a program that's supposed to count the number of days in between the given date and current date. Then it's supposed to calculate the number of years, months and remaining days between them from the calculated days. It's off by a couple of days for bigger dates. Any help would be greatly appreciated.
I've been trying it on dates such as 23.01.2076 and 23.01.1940 and changing the year and month one up or one down. For most of them it's off by 1-3 days.
HTML:
<html>
<head>
<meta charset="utf-8">
<script src="main.js"></script>
</head>
<body>
<div>
<input type="number" id="day" autocomplete="off">
<select id="month">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
<input type="number" id="year" autocomplete="off">
</div>
<input type="button" id="date-button" value="Count">
<div id="result" >
</div>
</body>
</html>
Javascript:
let gram_start, difference;
const one_day = 24*60*60*1000;
let months_list = {
"January": [1,31],
"February": [2,28],
"March": [3,31],
"April": [4,30],
"May": [5,31],
"June": [6,30],
"July": [7,31],
"August": [8,31],
"September": [9,30],
"October": [10,31],
"November": [11,30],
"December": [12,31]
};
let month_index = Object.keys(months_list);
function leapyear(year) {
return (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
}
window.onload = function count() {
document.getElementById("date-button").addEventListener("click", () => {
let years_write = 0;
let months_write = 0;
let day = parseInt(document.getElementById("day").value);
let month = document.getElementById("month").value;
let year = parseInt(document.getElementById("year").value);
let month_obj = months_list[month];
let target_date = new Date(year, month_obj[0]-1, day);
let today_date = new Date();
let matcher = new Date(today_date.getFullYear(),today_date.getMonth(), today_date.getDate());
//this works fine
if(target_date > today_date) {
gram_start = "There are that many days left to this date: <br>";
difference = Math.ceil((target_date - today_date) / one_day);
}
else if(target_date < today_date) {
gram_start = "There has been that many days since that date: <br>";
difference = Math.round((today_date - target_date) / one_day);
}
if(target_date < matcher)
difference--;
let remaining_days = difference;
if(target_date > today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year--;
}}
else if(target_date < today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year++;
}}
if(leapyear(year))
months_list.Luty[1] = 29;
else
months_list.Luty[1] = 28;
let i = month_obj[0]-1;
if(target_date > today_date) {
while(remaining_days >= (months_list[month_index[i]][1])) {
remaining_days -= (months_list[month_index[i]][1]);
months_write++;
i--;
}}
else if(target_date < today_date) {
while(remaining_days >= months_list[month_index[i]][1]) {
remaining_days -= months_list[month_index[i]][1];
months_write++;
i++;
}}
document.getElementById("result").innerHTML = gram_start + difference + " days, so:" + years_write + " years, " + months_write + " months and " + remaining_days + " days.";
})};

Populate dropdown list with current day, month and year using pure javascript

I found a question that interests me and a solution to it is here on this link: https://stackoverflow.com/a/51660131/17222337, but it's in jQuery, but I'm interested in a pure javascript solution. I reviewed what I could do, but found only non working code on this topic in pure javascript. I tried to translate from jQuery into javascript, but the code I get is wrong and does not work. Tell me please,
how to make a javascript code from the given jquery code?
I found solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
}
body{
min-height: 100vh;
display: flex;
justify-content: center;
align-items:center;
flex-direction: column;
}
form span{
display: block;
margin: 20px 0;
}
/*make form styling consistent across browsers*/
button, input, select, textarea {
font-family: inherit;
font-size: 100%;
}
</style>
</head>
<body>
<form>
<span>
<label for="day">Day:</label>
<select name="day" id="day"></select>
</span>
<span>
<label for="month">Month:</label>
<select name="month" id="month"></select>
</span>
<span>
<label for="year">Year:</label>
<select name="year" id="year">Year:</select>
</span>
</form>
<script>
//Create references to the dropdown's
const yearSelect = document.getElementById("year");
const monthSelect = document.getElementById("month");
const daySelect = document.getElementById("day");
const months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December'];
//Months are always the same
(function populateMonths(){
for(let i = 0; i < months.length; i++){
const option = document.createElement('option');
option.textContent = months[i];
monthSelect.appendChild(option);
}
monthSelect.value = "January";
})();
let previousDay;
function populateDays(month){
//Delete all of the children of the day dropdown
//if they do exist
while(daySelect.firstChild){
daySelect.removeChild(daySelect.firstChild);
}
//Holds the number of days in the month
let dayNum;
//Get the current year
let year = yearSelect.value;
if(month === 'January' || month === 'March' ||
month === 'May' || month === 'July' || month === 'August'
|| month === 'October' || month === 'December') {
dayNum = 31;
} else if(month === 'April' || month === 'June'
|| month === 'September' || month === 'November') {
dayNum = 30;
}else{
//Check for a leap year
if(new Date(year, 1, 29).getMonth() === 1){
dayNum = 29;
}else{
dayNum = 28;
}
}
//Insert the correct days into the day <select>
for(let i = 1; i <= dayNum; i++){
const option = document.createElement("option");
option.textContent = i;
daySelect.appendChild(option);
}
if(previousDay){
daySelect.value = previousDay;
if(daySelect.value === ""){
daySelect.value = previousDay - 1;
}
if(daySelect.value === ""){
daySelect.value = previousDay - 2;
}
if(daySelect.value === ""){
daySelect.value = previousDay - 3;
}
}
}
function populateYears(){
//Get the current year as a number
let year = new Date().getFullYear();
//Make the previous 100 years be an option
for(let i = 0; i < 101; i++){
const option = document.createElement("option");
option.textContent = year - i;
yearSelect.appendChild(option);
}
}
populateDays(monthSelect.value);
populateYears();
yearSelect.onchange = function() {
populateDays(monthSelect.value);
}
monthSelect.onchange = function() {
populateDays(monthSelect.value);
}
daySelect.onchange = function() {
previousDay = daySelect.value;
}
</script>
</body>
</html>

Contact Form 7 Datepicker: Automatically switch the date after a specified time of day

I'm using Contact Form 7 as a booking tool for a restaurant. The date you can book a table is set on next day by default. Also booking for the present day is not possible.
I want the tool to show the present date until 2pm and after 2pm it automatically switches to the next day's date. Also it makes booking for the present day unpossible after 2pm.
I'm a complete newbie in coding, I hope you guys can help me out.
This is how the Contact Form is currently set up:
<label> Personenanzahl *
[select* res-number "1 Person" "2 Personen" "3 Personen" "4 Personen" "5 Personen" "6 Personen"] </label>
<label> Datum *
[date* res-date id:datepicker min:today] </label>
<div class="vc_col-sm-6 padding-column"><label> Start *
[select* res-start id:start-time "17:00" "17:15" "17:30" "17:45" "18:00" "18:15" "18:30" "18:45"
"19:00" "19:15" "19:30" "19:45" "20:00" "20:15" "20:30" "20:45" "21:00" "21:15" "21:30" "21:45"
"22:00" "22:15" "22:30" "22:45" "23:00" "23:15" "23:30" "23:45" "00:00" "00:15" "00:30" "00:45"
"01:00"] </label></div>
<div class="vc_col-sm-6 padding-column"><label> Ende *
[select* res-end id:end-time "17:00" "17:15" "17:30" "17:45" "18:00" "18:15" "18:30" "18:45"
"19:00" "19:15" "19:30" "19:45" "20:00" "20:15" "20:30" "20:45" "21:00" "21:15" "21:30" "21:45"
"22:00" "22:15" "22:30" "22:45" "23:00" "23:15" "23:30" "23:45" "00:00" "00:15" "00:30" "00:45"
"01:00"] </label></div>
<label> Name *
[text* res-name] </label>
<label> Telefon *
[tel* res-tel] </label>
<label> E-Mail Adresse *
[email* res-email] </label>
[submit "Senden"]
And this is additional code which is implemented on the website:
<script type="text/javascript">
// initialize datepicker
var datepicker = jQuery('#datepicker');
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
var dd = today.getDate();
var mm = today.getMonth()+1; // January is 0!
var yyyy = today.getFullYear();
var tomday = tomorrow.getDate();
var tommonth = tomorrow.getMonth() + 1;
var tomyear = tomorrow.getFullYear();
if(tomday<10){tomday='0'+tomday} if(tommonth<10){tommonth='0'+tommonth} tomorrow = tomyear+'-'+tommonth+'-'+tomday;
jQuery(datepicker).attr('value', tomorrow);
// initialize time boxes
var startTimeBox = jQuery('#start-time')[0];
var endTimeBox = jQuery('#end-time')[0];
jQuery(startTimeBox).val("17:00");
jQuery(endTimeBox).val("18:45");
// handling of time changes
jQuery(startTimeBox).change(function (event) {
var startTimeValue = event.currentTarget.value;
var startHour = Number(startTimeValue.slice(0,2));
var startMinute = Number(startTimeValue.slice(3,5));
var endHour = 0;
var endMinute = 0;
if ((startHour == 23) || (startHour == 0) || (startHour == 1)) {
if ((startHour == 23) && (startMinute == 0)) {
endHour = 0;
endMinute = 45;
} else {
endHour = 1;
endMinute == 0;
}
} else {
if (startMinute == 0) {
endHour = startHour + 1;
endMinute = 45;
} else if (startMinute == 15) {
endHour = startHour + 2;
endMinute = 0;
} else if (startMinute == 30) {
endHour = startHour + 2;
endMinute = 15;
} else if (startMinute == 45) {
endHour = startHour + 2;
endMinute = 30;
}
if (endHour == 24) {
endHour = 0;
}
}
if (endHour == 24) {
endHour = 0;
}
var endHourString = endHour.toString();
var endMinuteString = endMinute.toString();
if (endHourString.length == 1) {
endHourString = "0" + endHourString;
}
if (endMinuteString.length == 1) {
endMinuteString = "0" + endMinuteString;
}
var endTimeString = endHourString + ":" + endMinuteString;
jQuery(endTimeBox).val(endTimeString);
});
</script>
Thank you very much!
You can use contact form7 date picker plugin its easy and usefull for time and date with curent tim

Show any Month/Year Javascript Calendar

I am trying to code a calendar using HTML and JavaScript that allows the user to choose any month in a given year to look at. I set up an HMTL form that has a drop down list to choose the month and an input box to enter the desired year. There are also buttons coded to toggle between the month and year, along with showing the current month. All of that is working, and I was able to get the calendar to show up as well for the current month.
What I am struggling with is getting the calendar display to change when I hit the toggle buttons or when I choose a desired month/year and hit the display button. I'm not sure what to do to get my calendar to work the way it is supposed to.
HTML
<!DOCTYPE html>
<html>
<head>
<script src = "CalendarFunction.js"></script>
<link href="Calendartest.css" rel="stylesheet"/>
</head>
<body onLoad = "CreateCalendar()">
<form name = "DateControl" id = "DateControl" onSubmit = "return false;" method = "post">
<!--Select the month and year to be shown -->
<select name = "Month" id = "month" onChange = "ChooseDate()">
<option value="January" id="January">January</option>
<option value="February" id="February">February</option>
<option value="March" id="March">March</option>
<option value="April" id="April">April</option>
<option value="May" id="May">May</option>
<option value="June" id="June">June</option>
<option value="July" id="July" >July</option>
<option value="August" id="August">August</option>
<option value="September" id="September">September</option>
<option value="October" id="October" >October</option>
<option value="November" id="November">November</option>
<option value="December" id="December">December</option>
</select>
<input name = "Year" type = "text" maxlength = "4">
<!-- Show Calendar -->
<input type = "button" name = "create" value = "Show" onClick = "ChooseDate()">
</TD>
</TR>
<!--Toggle between the months of the year -->
<input type = "button" name = "previousYear" value = "<Year" onClick = "PreviousYear()">
<input type = "button" name = "previousMonth" value = "<Month" onClick = "PreviousMonth()">
<input type = "button" name = "current" value = "Current" onClick = "SetDate()">
<input type = "button" name = "nextYear" value = ">Year" onClick = "NextYear()">
<input type = "button" name = "nextMonth" value = ">Month"onClick = "NextMonth()" >
</form>
<div id = "calendar"></div>
</body>
</html>
JS
function SetDate() {
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
this.focusDay = day;
document.DateControl.Month.selectedIndex = month;
document.DateControl.Year.value = year;
displayCalendar(month, year);
}
function isFourDigitYear(year) {
if (year.length != 4) {
alert("Sorry, the year must be four-digits in length.");
document.DateControl.Year.select();
document.DateControl.Year.focus();
} else {
return true;
}
}
function ChooseDate() {
var year = document.DateControl.Year.value;
if (isFourDigitYear(year)) {
var day = 0;
var month = document.DateControl.Month.selectedIndex;
displayCalendar(month, year);
}
}
function PreviousYear() {
var year = document.DateControl.Year.value;
if (isFourDigitYear(year)) {
var day = 0;
var month = document.DateControl.Month.selectedIndex;
year--;
document.DateControl.Year.value = year;
displayCalendar(month, year);
}
}
function PreviousMonth() {
var year = document.DateControl.Year.value;
if (isFourDigitYear(year)) {
var day = 0;
var month = document.DateControl.Month.selectedIndex;
if (month == 0) {
month = 11;
if (year > 1000) {
year--;
document.DateControl.Year.value = year;
}
} else {
month--;
}
document.DateControl.Month.selectedIndex = month;
displayCalendar(month, year);
}
}
function NextMonth() {
var year = document.DateControl.Year.value;
if (isFourDigitYear(year)) {
var day = 0;
var month = document.DateControl.Month.selectedIndex;
if (month == 11) {
month = 0;
year++;
document.DateControl.Year.value = year;
} else {
month++;
}
document.DateControl.Month.selectedIndex = month;
displayCalendar(month, year);
}
}
function NextYear() {
var year = document.DateControl.Year.value;
if (isFourDigitYear(year)) {
var day = 0;
var month = document.DateControl.Month.selectedIndex;
year++;
document.DateControl.Year.value = year;
displayCalendar(month, year);
}
}
function CreateCalendar() {
var htmlContent = "";
var FebNumberOfDays = "";
var counter = 1;
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
var nextMonth = month + 1;
var prevMonth = month - 1;
if (month == 1) {
if ((year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0)) {
FebNumberOfDays = 29;
} else {
FebNumberOfDays = 28;
}
}
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dayPerMonth = ["31", "" + FebNumberOfDays + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
var nextDate = new Date(nextMonth + ' 1 ,' + year);
var weekdays = nextDate.getDay();
var weekdays2 = weekdays;
var numOfDays = dayPerMonth[month];
while (weekdays > 0) {
htmlContent += "<td class='monthPre'></td>";
weekdays--;
}
while (counter <= numOfDays) {
if (weekdays2 > 6) {
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
if (counter == day) {
htmlContent += "<td class='dayNow'>" + counter + "</td>";
} else {
htmlContent += "<td class='monthNow'>" + counter + "</td>";
}
weekdays2++;
counter++;
}
var calendarBody = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>" +
monthNames[month] + " " + year + "</th></tr>";
calendarBody += "<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>" +
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
calendarBody += htmlContent;
calendarBody += "</tr></table>";
document.getElementById("calendar").innerHTML = calendarBody;
}
CSS
.monthPre{
color: gray;
text-align: center;
}
.monthNow{
color: blue;
text-align: center;
}
.dayNow{
border: 2px solid black;
color: #FF0;
text-align: center;
}
.calendar td{
htmlContent: 2px;
border: 2px solid black;
width: 140px;
height: 140px;
}
.monthNow th{
background-color: #000000;
color: #FFFFFF;
text-align: center;
}
.dayNames{
background: #0FF000;
color: #FFFFFF;
text-align: center;
}

jQuery UI Datepicker separate date/month+year

I want a datepicker like the one on booking.com.
It automatically changes the day+date of the month when a month+year in another select box is changed. I have had a look at the API of jQuery datepicker but I couldn't find anything that would help me.
See i Created One Fiddle Where you Select Date From DatePicker then it will change in Day/Month/year on Another Field . : Demo
$(function() {
$("#fullDate").datepicker({
onClose: function(dateText, inst) {
$('#year').val(dateText.split('/')[2]);
$('#month').val(dateText.split('/')[0]);
$('#day').val(dateText.split('/')[1]);
}
});
});
Thanks for your input. I finally figured how to get it working.
So here is the answer for anyone else who wants this kind of functionality.
HTML
<select name="day" id="day">
<option value="">Select Day</option>
</select>
<select name="month" id="month">
<option value="">Select Month</option>
</select>
JS
function getMonths() {
var months = new Array(12);
months[0] = "Jan";
months[1] = "Feb";
months[2] = "Mar";
months[3] = "Apr";
months[4] = "May";
months[5] = "Jun";
months[6] = "Jul";
months[7] = "Aug";
months[8] = "Sep";
months[9] = "Oct";
months[10] = "Nov";
months[11] = "Dec";
var d = new Date();
var month = d.getMonth();
var year = d.getFullYear();
var monthsArray = new Array(13);
for (var i = 0; i < 13; i++) {
var now = new Date();
if (now.getMonth() == 11) {
var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
var current = new Date(now.getFullYear(), now.getMonth() + i, 1);
}
monthsArray[current.getMonth() + 1 + '_' + current.getFullYear()] = months[current.getMonth()] + ' ' + current.getFullYear();
}
return monthsArray;
}
function getDaysInMonth(month, year, daySelector) {
var names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var date = new Date(year, month - 1, 1);
var days = [];
while (date.getMonth() == month - 1) {
days[date.getDate()] = (date.getDate() + " " + names[date.getDay()]);
date.setDate(date.getDate() + 1);
}
daySelector.find('option').remove();
daySelector.append($("<option></option>").attr("value", '').text("Day"));
for (var key in days) {
daySelector.append($("<option></option>").attr("value", key).text(days[key]));
}
}
var months = getMonths();
for (var key in months) {
$('#month')
.append($("<option></option>")
.attr("value", key)
.text(months[key]));
}
$('#month').change(function () {
var monthYear = $('#month').val().split('_');
getDaysInMonth(monthYear[0], monthYear[1], $('#day'));
});
Demo & Code

Categories