highlight a current date - javascript

I am beginner for programming. I got a code from online and I am modifying to get hands on js, jquery, jsp. What I am trying to get is I need to highlight a today's date. I tried many times but could not succeeded. Any help will be greatly appreciated.
$(document).ready(function () {
var Calendar = function(calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f=calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if(typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function() {
if ( this.CurrentMonth == 11 ) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function() {
if ( this.CurrentMonth == 0 ) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
//
Calendar.prototype.previousYear = function() {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function() {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function() {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function(y,m,n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m+1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for(var i=0; i < 7;i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i=0, z=0; z<6; z++) {
html += '<tr>';
for (var k= 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1){
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if ( d > lastDateOfCurrentMonth){
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function() {
// Start calendar
var c = new Calendar({
ParentID:"divcalendartable",
DaysOfWeek:[
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
Format:'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function(){
c.previousMonth();
};
getId('btnPrevYr').onclick = function(){
c.previousYear();
};
getId('btnNext').onclick = function(){
c.nextMonth();
};
getId('btnNextYr').onclick = function(){
c.nextYear();
};
}
// Get element by id
function getId(id) {
return document.getElementById(id);
}
});
html, body { margin: 0; padding: 0; }
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align:center;
}
.divcalendar {
padding: 15px;
float:left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>

Introduction: you don't need at all jQuery. Avoid to insert into jQuery Dom ready event the window.onload. It's useless.
The fast way to achieve your goal is:
Define a new css class:
.currentDay {
background-color: green !important;
}
In the method "Calendar.prototype.Calendar = function (y, m, n) {" change these lines:
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
with:
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() &&
this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
The previous change adds the class currentDay to today.
var Calendar = function (calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f = calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if (typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function () {
if (this.CurrentMonth == 11) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function () {
if (this.CurrentMonth == 0) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
Calendar.prototype.previousYear = function () {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function () {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function () {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function (y, m, n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m + 1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y - 1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for (var i = 0; i < 7; i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i = 0, z = 0; z < 6; z++) {
html += '<tr>';
for (var k = 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1) {
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if (d > lastDateOfCurrentMonth) {
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() && this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function () {
// Start calendar
var c = new Calendar({
ParentID: "divcalendartable",
DaysOfWeek: [
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
Format: 'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function () {
c.previousMonth();
};
getId('btnPrevYr').onclick = function () {
c.previousYear();
};
getId('btnNext').onclick = function () {
c.nextMonth();
};
getId('btnNextYr').onclick = function () {
c.nextYear();
};
// Get element by id
function getId(id) {
return document.getElementById(id);
}
}
html, body {
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align: center;
}
.divcalendar {
padding: 15px;
float: left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.currentDay {
background-color: green !important;
}
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>

I guess you need to include jQuery.js.
https://learn.jquery.com/using-jquery-core/document-ready/

Related

JS Calendar breaks on certain months

everyone!
I am fairly new to the coding field, I was trying to create a JS calendar that starts with Monday but it breaks on certain months, like that:
Screenshot
I think it happens only when monday is the first day of the month and only for upcoming months.
var Cal = function(divId) {
//Store div id
this.divId = divId;
// Days of week, starting on Sunday
this.DaysOfWeek = [
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
'Sun'
];
// Months, stating on January
this.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
// Set the current month, year
var d = new Date();
this.currMonth = d.getMonth();
this.currYear = d.getFullYear();
this.currDay = d.getDate();
};
// Goes to next month
Cal.prototype.nextMonth = function() {
if ( this.currMonth == 11 ) {
this.currMonth = 0;
this.currYear = this.currYear + 1;
}
else {
this.currMonth = this.currMonth + 1;
}
this.showcurr();
};
// Goes to previous month
Cal.prototype.previousMonth = function() {
if ( this.currMonth == 0 ) {
this.currMonth = 11;
this.currYear = this.currYear - 1;
}
else {
this.currMonth = this.currMonth - 1;
}
this.showcurr();
};
// Show current month
Cal.prototype.showcurr = function() {
this.showMonth(this.currYear, this.currMonth);
};
// Show month (year, month)
Cal.prototype.showMonth = function(y, m) {
var d = new Date()
// First day of the week in the selected month
, firstDayOfMonth = new Date(y, m, 1).getDay()
// Last day of the selected month
, lastDateOfMonth = new Date(y, m+1, 0).getDate()
// Last day of the previous month
, lastDayOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
var html = '<table>';
// Write selected month and year
html += '<thead><tr>';
html += '<td colspan="7" class="header">' + this.Months[m] + ' ' + y + '</td>';
html += '</tr></thead>';
// Write the header of the days of the week
html += '<tr class="days">';
for(var i=0; i < this.DaysOfWeek.length;i++) {
html += '<td>' + this.DaysOfWeek[i] + '</td>';
}
html += '</tr>';
// Write the days
var i=1;
do {
var dow = new Date(y, m, i).getDay();
// If Sunday, start new row
if ( dow == 1 ) {
html += '<tr>';
}
// If not Sunday but first day of the month
// it will write the last days from the previous month
else if ( i == 1 ) {
html += '<tr>';
var k = lastDayOfLastMonth - firstDayOfMonth;
for(var j=1; j < firstDayOfMonth; j++) {
html += '<td class="not-current">' + k + '</td>';
k++;
}
}
// Write the current day in the loop
var chk = new Date();
var chkY = chk.getFullYear();
var chkM = chk.getMonth();
if (chkY == this.currYear && chkM == this.currMonth && i == this.currDay) {
html += '<td class="today">' + i + '</td>';
} else {
html += '<td class="normal">' + i + '</td>';
}
// If Saturday, closes the row
if ( dow == 0 ) {
html += '</tr>';
}
// If not Saturday, but last day of the selected month
// it will write the next few days from the next month
else if ( i == lastDateOfMonth ) {
var k=7;
for(dow; dow < 7; dow++) {
html += '<td class="not-current">' + k + '</td>';
k++;
}
}
i++;
}while(i <= lastDateOfMonth);
// Closes table
html += '</table>';
// Write HTML to the div
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function() {
// Start calendar
var c = new Cal("divCal");
c.showcurr();
// Bind next and previous button clicks
getId('btnNext').onclick = function() {
c.nextMonth();
};
getId('btnPrev').onclick = function() {
c.previousMonth();
};
}
// Get element by id
function getId(id) {
return document.getElementById(id);
}
html,
body {
height: 100%;
}
body {
font-size: 100%;
line-height: 1.5;
font-family: monospace;
background: #fff;
color: #fff;
}
*,
*:before,
*:after {
box-sizing: border-box;
}
.group:after {
content: "";
display: table;
clear: both;
}
img {
max-width: 100%;
height: auto;
vertical-align: baseline;
}
a {
text-decoration: none;
}
.calendar-wrapper {
width: 360px;
margin: 3em auto;
padding: 2em;
border: 1px solid black;
border-radius: 5px;
background: #fff;
box-shadow: 2px 2px 1px 0px #000000;
}
table {
clear: both;
width: 100%;
border: 2px solid black;
border-radius: 3px;
border-collapse: collapse;
color: #444;
}
td {
height: 48px;
text-align: center;
vertical-align: middle;
border-right: 2px solid black;
border-top: 2px solid black;
width: 14.28571429%;
}
td.header {
background: #f3fff3;
font-weight: bold;
}
td.not-current {
color: #c0c0c0;
}
td.today {
font-weight: 700;
color: #28283b;
font-size: 1.5em;
}
thead td {
border: none;
color: #28283b;
text-transform: uppercase;
font-size: 1.5em;
}
#btnPrev {
float: left;
margin-bottom: 20px;
}
#btnPrev:before {
content: '\f104';
font-family: FontAwesome;
padding-right: 4px;
}
#btnNext {
float: right;
margin-bottom: 20px;
}
#btnNext:after {
content: '\f105';
font-family: FontAwesome;
padding-left: 4px;
}
#btnPrev,
#btnNext {
background: transparent;
border: none;
outline: none;
font-size: 1em;
color: #c0c0c0;
cursor: pointer;
font-family: monospace;
text-transform: uppercase;
transition: all 0.3s ease;
}
#btnPrev:hover,
#btnNext:hover {
color: #28283b;
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Calendar Widget for Notion by Neon</title>
<meta name='viewport' content='width=device-width, initial-scale=1'><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet' href='//fonts.googleapis.com/css?family=Roboto:400|Roboto+Condensed:400|Fjalla+One:400'>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css'>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="calendar-wrapper">
<button id="btnPrev" type="button">Prev</button>
<button id="btnNext" type="button">Next</button>
<div id="divCal"></div>
</div>
<!-- partial -->
<script src="./script.js"></script>
</body>
</html>
Would love if anyone could provide any guidance to this issue.

push new items to an object from fields

actually i'm about to create a calendar with events, and i want to add new events with a form, let me explain.
i have:
let eventsArray = [
{
id: 'my event name',
date: '2021/08/23',
content: 'my events description',
},
];
result and demo:
https://jsfiddle.net/er73av8h/
Now, i want to populate this object through 3 field maybe (id, date and content), but i'm not sure on how i can do this.
I made a very simple example of what you want.
If my example works for you I will write a description of how this code works.
Example:
let eventsArray = [
{
id: 'my event name',
date: '2021/08/23',
content: 'my events description',
},
];
let wrp = document.getElementById('calendar');
function addInfoInCalendar() {
wrp.innerHTML = '';
for (const iterator of eventsArray) {
wrp.innerHTML += '<div>' + iterator.id + ' ' + iterator.date + ' ' + iterator.content + '</div>';
}
}
addInfoInCalendar();
let formWrp = document.getElementById('myForm');
let f_id = myForm.querySelectorAll('[name="id"]')[0];
let f_date = myForm.querySelectorAll('[name="date"]')[0];
let f_content = myForm.querySelectorAll('[name="content"]')[0];
let f_button = myForm.querySelector('button');
f_button.addEventListener('click', addNewInfo);
function addNewInfo() {
eventsArray.push({
id: f_id.value,
date: f_date.value,
content: f_content.value
});
addInfoInCalendar();
}
<div id="myForm">
<input type="text" name="id">
<input type="date" name="date">
<input type="text" name="content">
<button>Send</button>
</div>
<div id="calendar"></div>
Example 2:
In this example is your code! I added a few new lines at the end of the code and marked them with a comment.
let eventsArray = [
{
id: 'My Name',
date: '2021/08/23',
content: 'my events description',
source: '#',
},
];
let today = new Date(),
currentMonth = today.getMonth(),
currentYear = today.getFullYear();
// array for weeks
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// array for month
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// structure
let structureCalendar = createElement('div', window.root, {
id: 'structureCalendar',
}),
// header
calendarHeader = createElement('header', structureCalendar, {}),
// header columns left center and right
headerLeft = createElement('div', calendarHeader, { className: 'left' }),
headerCenter = createElement('div', calendarHeader, { className: 'center' }),
headerRight = createElement('div', calendarHeader, { className: 'right' }),
// inside left column
buttonPrev = createElement('button', headerLeft, { textContent: 'Previous' }),
buttonNext = createElement('button', headerLeft, { textContent: 'Next' }),
centerTitle = createElement('h1', headerCenter, {
textContent: months[currentMonth] + ' ' + currentYear,
}),
// calendar body
calendarBody = createElement('div', structureCalendar, { id: 'calendar' }),
weekdayBody = createElement('ul', calendarBody, { id: 'weekdays' }),
daysBody = createElement('ul', calendarBody, { id: 'days' });
// init calendar
showCalendar(currentMonth, currentYear);
// map week days
weekdays.map((item, i) =>
// change to monday
today.getDay() - 0 == i
? createElement('li', weekdayBody, { className: 'today', textContent: item })
: createElement('li', weekdayBody, { textContent: item })
);
// buttons next prev
buttonPrev.onclick = () => prev();
buttonNext.onclick = () => next();
// generate calendar
function showCalendar(month, year) {
// first day - 1
let firstDay = new Date(year, month).getDay() - 1;
// clear preview content
daysBody.textContent = '';
// filing data about month and in the page via DOM.
centerTitle.textContent = months[month] + ' ' + year;
// creating all cells
let date = 1;
for (let i = 0; i < 6; i++) {
//creating individual cells, filing them up with data.
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
createElement('li', daysBody, { textContent: '' });
} else if (date > daysInMonth(month, year)) {
break;
} else {
let li = createElement('li', daysBody, {}),
info = createElement('div', li, {
className: 'info',
textContent: weekdays[j],
}),
div = createElement('div', li, { className: 'date', textContent: date });
// ----------------------------
// ----- view events
if (typeof eventsArray !== 'undefined') {
viewEvents(eventsArray, li, [year, month, date]);
}
// ----------------------------
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
li.className = 'today';
}
date++;
}
}
}
}
// view events
function viewEvents(data, where, args) {
return (
data &&
data.map((item) => {
let date = item.date.split('/'),
year = parseInt(date[0]),
month = parseInt(date[1]) - 1,
day = parseInt(date[2]);
if (year === args[0] && month === args[1] && day === args[2]) {
let event = createElement('div', where, { className: 'ev', id: item.id }),
eventDesc = createElement('div', event, { className: 'ev-desc' });
eventDesc.innerHTML = `<div class="eventFlarumCalendar">${item.content}</div>`;
event.onclick = () => alert(eventDesc.textContent);
}
})
);
}
// next month
function next() {
currentMonth = (currentMonth + 1) % 12;
currentYear = currentMonth === 11 ? currentYear + 1 : currentYear;
showCalendar(currentMonth, currentYear);
}
// previus month
function prev() {
currentMonth = currentMonth === 0 ? 11 : currentMonth - 1;
currentYear = currentMonth === 0 ? currentYear - 1 : currentYear;
showCalendar(currentMonth, currentYear);
}
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
// --- Create element
function createElement(element, where, args) {
let d = document.createElement(element);
if (args) for (const [k, v] of Object.entries(args)) d[k] = v;
where.appendChild(d);
return d;
}
/////////////////////////////////////////////////////////////
// NEW LINES
let formWrp = document.getElementById('myForm');
let f_id = myForm.querySelectorAll('[name="id"]')[0];
let f_date = myForm.querySelectorAll('[name="date"]')[0];
let f_content = myForm.querySelectorAll('[name="content"]')[0];
let f_button = myForm.querySelector('button');
f_button.addEventListener('click', addNewInfo);
function addNewInfo() {
let nfd = f_date.value.split('-').join('/');
eventsArray.push({
id: f_id.value,
date: nfd,
content: f_content.value
});
showCalendar(currentMonth, currentYear);
}
.eventFlarumCalendar {
cursor: help;
}
#structureCalendar header {
height: 4rem;
line-height: 4rem;
text-align: center;
background: #ff6200;
color: #fdfdfd;
}
#structureCalendar header .left,
#structureCalendar header .center,
#structureCalendar header .right {
width: 100%;
float: left;
}
#structureCalendar header .left h1,
#structureCalendar header .center h1,
#structureCalendar header .right h1 {
line-height: 1.8rem;
font-size: 25px;
}
#structureCalendar header .left button,
#structureCalendar header .center button,
#structureCalendar header .right button {
background-color: #ff6200;
border: 1px solid #ff6200;
color: #fdfdfd;
padding: 0.5rem 1rem;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 0 4px;
cursor: pointer;
transition: all 500ms ease;
}
.center {
background: #ff6200;
}
#structureCalendar header .left button:hover,
#structureCalendar header .center button:hover,
#structureCalendar header .right button:hover {
background-color: #ff6200;
border-color: #ff6200;
color: #fdfdfd;
transition: all 500ms ease;
}
#calendar #days,
#calendar #weekdays {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
}
#calendar #days li,
#calendar #weekdays li {
display: block;
float: left;
width: calc(100% / 7);
padding: 5px;
box-sizing: border-box;
}
#calendar #weekdays {
height: 40px;
background: #ff6200;
border-bottom: 2px solid #ff6200;
}
.contentcalflarum {
display: flow-root;
}
#calendar #weekdays li {
text-align: center;
text-transform: uppercase;
line-height: 20px;
border: none !important;
padding: 10px 6px;
color: #474747;
font-size: 13px;
font-weight: bold;
}
#calendar #weekdays .today {
background: #ff6200;
color: #fdfdfd;
}
#calendar #days li {
height: 150px;
overflow-y: auto;
background: #fdfdfd;
position: relative;
color: #ff6200;
border: 1px solid #f0f0f0;
}
#calendar #days li:hover {
background: #f0f0f0;
}
#calendar #days li .info {
position: absolute;
bottom: 2px;
right: 2px;
opacity: 0;
}
#calendar #days li .date {
text-align: center;
margin-bottom: 5px;
background: #777ffa;
color: #fdfdfd;
width: 25px;
height: 25px;
line-height: 25px;
border-radius: 50%;
float: right;
font-size: 12px;
font-weight: bold;
}
#calendar #days .today {
background: #f2f2fe;
}
#calendar #days .today:hover {
background: #c0c4fd;
}
.ev {
display: block;
background: #f2f2fe;
border: 1px solid #c0c4fd;
border-radius: 4px;
margin: 5px auto;
transition: background 500ms ease;
}
.ev:hover {
background: #777ffa;
transition: background 500ms ease;
}
.ev-desc {
padding: 0.2rem 0.5rem;
}
.ev-desc a {
text-decoration: none;
color: #ff6200;
transition: color 500ms ease;
}
.ev:hover .ev-desc a {
color: #a8adfc;
transition: color 500ms ease;
}
#media (max-width: 768px) {
#structureCalendar header {
height: auto;
text-align: center;
padding: 1rem;
}
#structureCalendar header .left,
#structureCalendar header .center,
#structureCalendar header .right {
width: 100%;
float: none;
}
#calendar #weekdays,
#calendar .null {
display: none;
}
#calendar #days li {
height: auto !important;
border: 1px solid #f0f0f0;
width: 100%;
padding: 10px;
margin-bottom: -1px;
}
#calendar #days li .info {
left: 2px;
opacity: 1;
color: #d9dbfe;
}
#calendar .date {
float: none;
}
}
<div id="myForm">
<input type="text" name="id">
<input type="date" name="date">
<input type="text" name="content">
<button>Send</button>
</div>
<div class="contentcalflarum">
<div class="calforflarum" id="root"></div>
</div>
you can write function to add event to the array
const addEvent = (id, event, content) => {
eventsArray.push({id, event, content})
}
And to access
for (let i = 0; i < eventsArray.length; i++) {
const event = eventsArray[i]
console.log(`This is id: ${event['id']}`)
console.log(`This is event: ${event['event']}`)
console.log(`This is content: ${event['content']}`)
}
You can use the current date as object property and then based on that date push your event and content. i.e:
8142021; //8 = month, 14 = date; 2021= year
let eventsArray = {
$8142021: [
{
id: 1,
name: 'my event name',
content: 'my events description',
},
{
id: 2,
name: 'my event',
content: 'my events description',
}
],
$8152021: [
{
id: 1,
name: 'my event name',
content: 'my events description',
},
{
id: 2,
name: 'my event',
content: 'my events description',
}
],
};
]

javascript function causing postback on asp.net

This following javascript is causing an unwanted postback on asp.net webform codebehind:
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});`
It's from a calendar control and the function is called when you click on a date. Adding e.preventDefault() stops the postback but then showEvent() is not called. On a plain html page everything works fine, but I need this on an aspx page cause I need to pull the events from db, server side. I hope someone could come up with a solution, since the author himself does not seem to be able to come up with one.
Ok, here's the aspx page:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="caltest.aspx.vb" Inherits="caltest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="css/mini-event-calendar.css" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="js/mini-event-calendar.js?v=7"></script>
<script>
var db_events = [
{
title: "Board members meeting.",
date: 1532381440036,
link: "events.com/ev2"
},
{
title: "Delaware branch opening.",
date: 1532467961534,
link: "events.com/ev1"
},
{
title: "An important event.",
date: 1532554405128,
link: "events.com/ev1"
}
];
$(document).ready(function () {
$("#calendar").MEC({
calendar_link: "example.com/myCalendar",
events: db_events
});
//if you don't have events, use
// $("#calendar2").MEC();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>With events...</h3>
<div id="calendar" runat="server" style="width: 30%;margin-right:auto;margin-left:auto;"></div> <br>
</div>
</form>
</body>
</html>
mini-event-calendar.js
(function( $ ) {
var calenderTpl = '<div id="calTitle"><button class="month-mover prev"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button><div id="monthYear"></div><button class="month-mover next"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button></div><div><div id="calThead"><div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div></div><div id="calTbody"></div></div><div id="calTFooter"><h3 id="eventTitle">No events today.</h3>ALL EVENTS</div>';
var short_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date();
var cur_month = today.getMonth();
var cur_year = today.getFullYear();
$.fn.miniEventCalendar = $.fn.MEC = function(options) {
var settings = $.extend({
calendar_link : "",
events: []
}, options );
var mini_cal = this;
mini_cal.addClass('mini-cal').html(calenderTpl);
var tbody = mini_cal.find("#calTbody");
var cal_title = mini_cal.find("#monthYear");
var cal_footer = mini_cal.find("#calTFooter");
var event_title = mini_cal.find("#eventTitle");
var events_link = mini_cal.find("#calLink");
cal_title.text("Feb 2018");
event_title.text("No events today.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
if(!settings.calendar_link.length && !settings.events.length)
cal_footer.css("display", "none");
mini_cal.find(".month-mover").each(function(){
var mover = $(this);
mover.bind("click", function(){
if(mover.hasClass("next"))
viewNextMonth();
else
viewPrevMonth();
});
});
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});
function populateCalendar(month, year) {
tbody.html("");
cal_title.text(short_months[month] + " " + year);
cur_month = month;
cur_year = year;
var ldate = new Date(year, month);
var dt = new Date(ldate);
if(ldate.getDate() === 1 && dt.getDay() != 1)
tbody.append(last_prev_month_days(dt.getDay()));
while (ldate.getMonth() === month) {
dt = new Date(ldate);
var isToday = areSameDate(ldate, new Date());
var event = null;
var event_index = settings.events.findIndex(function(ev) {
return areSameDate(dt, new Date(ev.date));
});
if(event_index != -1){
event = settings.events[event_index];
if(isToday)
showEvent(event);
}
tbody.append(date_tpl(false, ldate.getDate(), isToday, event));
ldate.setDate(ldate.getDate() + 1);
var buffer_days = 43 - mini_cal.find(".a-date").length;
if(ldate.getMonth() != month)
for (var i = 1; i < buffer_days; i++)
tbody.append(date_tpl(true, i));
}
}
function last_prev_month_days(day){
if(cur_month > 0){
var month_idx = cur_month - 1;
var year_idx = cur_year;
}else{
if(cur_month < 11){
var month_idx = 0;
var year_idx = cur_year + 1;
}else{
var month_idx = 11;
var year_idx = cur_year - 1;
}
}
var prev_month = getMonthDays(month_idx, year_idx);
var last_days = "";
for (var i = day; i > 0; i--)
last_days += date_tpl(true, prev_month[ prev_month.length - i]);
return last_days;
}
function date_tpl(blurred, date, is_today, event){
var tpl = "<div class='a-date blurred'><span>"+date+"</span></div>";
if(!blurred){
var cls = is_today ? "current " : "";
cls += event && event !== null ? "event " : "";
var tpl ="<button class='a-date "+cls+"' data-event='"+JSON.stringify(event)+"'><span>"+date+"</span></button>";
}
return tpl;
}
function showEvent(event){
if(event && event !== null && event !== undefined){
event_title.text(event.title);
events_link.text("VIEW EVENT");
events_link.attr("href", event.link);
}else{
event_title.text("No events on this day.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
}
}
function viewNextMonth(){
var next_month = cur_month < 11 ? cur_month + 1 : 0;
var next_year = cur_month < 11 ? cur_year : cur_year + 1;
populateCalendar(next_month, next_year);
}
function viewPrevMonth(){
var prev_month = cur_month > 0 ? cur_month - 1 : 11;
var prev_year = cur_month > 0 ? cur_year : cur_year - 1;
populateCalendar(prev_month, prev_year);
}
function areSameDate(d1, d2) {
return d1.getFullYear() == d2.getFullYear()
&& d1.getMonth() == d2.getMonth()
&& d1.getDate() == d2.getDate();
}
function getMonthDays(month, year) {
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
days.push(date.getDate());
date.setDate(date.getDate() + 1);
}
return days;
}
populateCalendar(cur_month, cur_year);
return mini_cal;
};
}( jQuery ));
mini-event-calendar.css
.mini-cal{
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
font-family: Verdana, sans-serif;
padding-bottom: 1.2em;
background: #22252e;
color: #fff;
}
#calTitle{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.12em;
text-align: center;
padding: 0.4em 1em;
padding-top: 0.8em;
}
#calTitle button{
outline: none;
display: block;
border: 0.1em solid #ddd;
border: none;
padding: 0;
width: 40px;
height: 40px;
line-height: 60px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
}
#calTitle button svg{
width: 30px;
height: 30px;
}
#calTitle button:hover{
background: rgba(255,255,255,0.1);
}
#calThead, #calTbody{
display: flex;
flex-wrap: wrap;
padding: 0.1em;
}
#calThead{
color: #fff;
margin-top: 0.4em;
align-items: center;
text-align: center;
font-size: 0.88em;
}
#calThead > div, #calTbody .a-date{
box-sizing: border-box;
flex: 1;
min-width: calc(100% / 7);
max-width: calc(100% / 7);
width: calc(100% / 7);
text-align: center;
padding: 0;
}
#calThead > div{
font-size: 1.1em;
padding: 0.2em 0.2em;
}
#calTbody{
color: #ddd;
}
#calTbody .a-date > span{
display: block;
font-size: 1em;
}
#calTbody .a-date{
cursor: default;
padding: 0;
position: relative;
background-color: transparent;
color: inherit;
padding: 1em;
border: 0.1em solid transparent;
outline: none;
font-size: 0.9em;
}
#calTbody .a-date.blurred{
opacity: 0.5;
pointer-events: none;
}
#calTbody .a-date.event:before{
content: '';
position: absolute;
top: 0.2em;
right: 0;
left: 0;
margin: auto;
background-color: #fffc23;
width: 0.3em;
height: 0.3em;
border-radius: 50%;
}
#calTbody .a-date.current{
border-color: #fffc23;
outline: none;
outline: 0;
}
#calTbody .a-date.current.event{
background-color: #fffc23;
color: #000;
}
#calTbody .a-date:focus,
#calTbody .a-date:active{
background: #3f4042;
}
#calTFooter{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.1em;
padding: 0 1em;
margin-top: 0.5em;
}
#calTFooter #calLink{
font-size: 0.8em;
display: inline-block;
padding: 0.6em 0.8em;
flex-shrink: 0;
text-decoration: none;
color: #fffc23;
}
#calTFooter #calLink:hover{
background-color: #555;
}
#calTFooter #eventTitle{
margin: 0;
margin-right: 0.1em;
font-weight: normal;
font-size: 0.95em;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}

Data input auto formatting using Javascript

I'm working on a date input auto formatting solution. The code I use adds a space between before and after a slash (example : 02 / 02 / 2006.
I tried to avoid this behavior. So instead, the date format is 02/02/2006.
I'm also using an Event Delegation to make the date formatting active on all the inputs.
Actually, I tried a solution to deactivate space adding. But the modification doesn't allow the control of the input to delete dates.
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
function dateInput(date) { // date is input object argument
var input = date.value;
if (/\D\/$/.test(input))
input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) {
values[0] = checkValue(values[0], 12);
}
if (values[1]) {
values[1] = checkValue(values[1], 31);
}
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
date.value = output.join('').substr(0, 14);
}
function dateBlur(date) { // date is input object argument
var input = date.value;
var values = input.split('/').map(function(v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function(v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
}
}
date.value = output;
}
// delegate event handling from the form element
var form = document.getElementById("form");
form.addEventListener("blur", function(e) {
if(e.target.dataset.type == "date") {
dateBlur(e.target);
}
},false);
form.addEventListener("input", function(e) {
if(e.target.dataset.type == "date") {
dateInput(e.target);
}
}, false);
html {
box-sizing: border-box;
font-family: 'PT Sans', sans-serif;
-webkit-font-smoothing: antialiased;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background-color: #f3f3f3;
}
form {
width: 100%;
max-width: 400px;
margin: 60px auto;
}
form input {
font-size: 30px;
padding: 0 20px;
border: 2px solid #ccc;
width: 100%;
color: #666;
line-height: 3;
border-radius: 7px;
font-family: 'PT Sans', sans-serif;
font-weight: bold;
}
form input:focus {
outline: 0;
}
form input.error {
border-color: #ff0000;
}
form label.error {
background-color: #ff0000;
color: #fff;
padding: 6px;
font-size: 11px;
}
label {
color: #999;
display: block;
margin-bottom: 10px;
text-transform: uppercase;
font-size: 18px;
font-weight: bold;
letter-spacing: 0.05em
}
form small {
color: #888;
font-size: 1em;
margin-top: 10px;
display: block;
align-self: ;
}
<form id="form" method="post" action="">
<label for="amount">Date</label>
<input type="text" id="date1" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 2</label>
<input type="text" id="date2" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 3</label>
<input type="text" id="date3" data-type="date" />
<small>Enter date as Month / Day / Year</small>
</form>
First you need to remove ' / ' and replace with '/',
And you need to change substr(0, 14) to substr(0, 10)
You can also specify maxlength="10" to your html input box
Try following snippet.
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
function dateInput(date) { // date is input object argument
var input = date.value;
if (/\D\/$/.test(input))
input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) {
values[0] = checkValue(values[0], 12);
}
if (values[1]) {
values[1] = checkValue(values[1], 31);
}
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + '/' : v;
});
date.value = output.join('').substr(0, 10);
}
function dateBlur(date) { // date is input object argument
var input = date.value;
var values = input.split('/').map(function(v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function(v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join('/');
}
}
date.value = output;
}
// delegate event handling from the form element
var form = document.getElementById("form");
form.addEventListener("blur", function(e) {
if(e.target.dataset.type == "date") {
dateBlur(e.target);
}
},false);
form.addEventListener("input", function(e) {
if(e.target.dataset.type == "date") {
dateInput(e.target);
}
}, false);
html {
box-sizing: border-box;
font-family: 'PT Sans', sans-serif;
-webkit-font-smoothing: antialiased;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
background-color: #f3f3f3;
}
form {
width: 100%;
max-width: 400px;
margin: 60px auto;
}
form input {
font-size: 30px;
padding: 0 20px;
border: 2px solid #ccc;
width: 100%;
color: #666;
line-height: 3;
border-radius: 7px;
font-family: 'PT Sans', sans-serif;
font-weight: bold;
}
form input:focus {
outline: 0;
}
form input.error {
border-color: #ff0000;
}
form label.error {
background-color: #ff0000;
color: #fff;
padding: 6px;
font-size: 11px;
}
label {
color: #999;
display: block;
margin-bottom: 10px;
text-transform: uppercase;
font-size: 18px;
font-weight: bold;
letter-spacing: 0.05em
}
form small {
color: #888;
font-size: 1em;
margin-top: 10px;
display: block;
align-self: ;
}
<form id="form" method="post" action="">
<label for="amount">Date</label>
<input type="text" id="date1" data-type="date" maxlength="10"/>
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 2</label>
<input type="text" id="date2" data-type="date" maxlength="10"/>
<small>Enter date as Month / Day / Year</small>
</br>
<label for="amount">Date 3</label>
<input type="text" id="date3" data-type="date" maxlength="10" />
<small>Enter date as Month / Day / Year</small>
</form>

Loop through the list of dynamically added input type radio list in javascript

I have a function MultiChoiceQues(theSeq, theQues, theChoices theAns). I then add the theQues in a p tag followed by the unordered list of all the respective options with an input of type radio for each option.
In an array variable allQues[] I created multiple instance for the function MultiChoiceQues passing different arguments. Now, on load I'm showing all the questions with their respective options.
How can I access and highlight all the correct answers?
var content = "";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="' + theSeq + '"/> ' + eachChoice + '</li>';
});
content += '</ul>';
return content;
console.log(content);
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
];
function ShowAllQues() {
document.getElementById("container").innerHTML = content;
}
function ShowAllAns() {
/* Highlight all the correct answers */
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul {
list-style: none;
}
ul li:hover {
cursor: pointer;
color: #5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor: pointer;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus {
outline: 0;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns(); return false;">
</body>
Add the getAnswer method to your MultiChoiceQues constructor.
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
});
content+='</ul>';
this.getAnswer = function () {
return theAns;
}
}
Then this is your answers function.
function ShowAllAns(){
/* Highlight all the correct answers */
var answers = allQues.map(function (question) {
return question.getAnswer();
})
var question_lists = document.getElementById("container").getElementsByTagName('ul');
for (var i = 0; i < question_lists.length; i++) {
var answer_index = answers[i];
var items = question_lists[i].childNodes;
items[answer_index - 1].style.background = "red";
}
}
https://jsfiddle.net/1prr4m7f/3/
tl;dr:
Add Class <ul class="answerChoicesGroup">
Replace return content with this.answer = theAns;
Create var getting answerChoicesGroup: answerChoicesGroup = document.getElementsByClassName('answerChoicesGroup');
Insert in showAllAns() the following:
.
function ShowAllAns() {
/* Highlight all the correct answers */
for (i = 0; i < allQues.length; i++) {
// Get the current answer group
var answerGroup = answerChoicesGroup[i],
// Access the correct radio input answer by getting the answer index from `allQues`
correctAnswer = answerGroup.children[allQues[i].answer - 1];
// Do whatever you'd like with `correctAnswer`
correctAnswer.firstElementChild.checked = true;
correctAnswer.classList.add('answer');
}
}
Explanation
You are on the right track by return content. Instead of that, (which won't return content because you have the keyword new) I just did this.answer = theAns. answer can be any word you'd like.
The way to access answer would be like any object. i.e.
var muiltipleChoiceQuestion = new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
alert(muiltipleChoiceQuestion.answer) // result: 4
The next thing I did was, added a class name to all the ul's called answerChoicesGroup, and created a variable for that too.
In showAllAns() function, I iterated through allQues, and accessed the correct answer by:
Get the current answer group. (var answerGroup)
Access the correct radio input answer by getting the answer index from allQues. (var correctAnswer)
Do whatever you'd like with correctAnswer.
Here's the code:
Here's how you would do it:
JSFiddle
var content = "";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul class="answerChoicesGroup">';
theChoices.forEach(function(eachChoice) {
content += '<li><input type="radio" name="' + theSeq + '"/> ' + eachChoice + '</li>';
});
content += '</ul>';
this.answer = theAns;
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
],
answerChoicesGroup = document.getElementsByClassName('answerChoicesGroup');
function ShowAllQues() {
document.getElementById("container").innerHTML = content;
}
function ShowAllAns() {
/* Highlight all the correct answers */
for (i = 0; i < allQues.length; i++) {
// Get the current answer group
var answerGroup = answerChoicesGroup[i],
// Access the correct radio input answer by getting the answer index from `allQues`
correctAnswer = answerGroup.children[allQues[i].answer - 1];
// Do whatever you'd like with `correctAnswer`
correctAnswer.firstElementChild.checked = true;
correctAnswer.classList.add('answer');
}
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul {
list-style: none;
}
ul li:hover {
cursor: pointer;
color: #5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor: pointer;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus {
outline: 0;
}
.answer {
color: green;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns();">
</body>
Try this with jQuery:
var content="";
function MultiChoiceQues(theSeq, theQues, theChoices, theAns) {
content += '<p>' + theQues + '</p> <ul>';
theChoices.forEach(function(eachChoice,index) {
if(index == theAns-1){
content += '<li class="options answer"><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
}else{
content += '<li class="options"><input type="radio" name="'+ theSeq +'"/> ' + eachChoice + '</li>';
}
});
content+='</ul>';
return content;
}
var allQues = [
new MultiChoiceQues(1, "Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 4),
new MultiChoiceQues(2, "What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília", "Salvador"], 3),
new MultiChoiceQues(3, "Who won the French open 2016 in Men’s Single category?", ["Novak Djokovic", "Andy Murray", "Rafael Nadal"], 1)
];
function ShowAllQues(){
document.getElementById("container").innerHTML=content;
}
function ShowAllAns(){
$(".answer").addClass("green");
}
body {
background: #f2f2f3;
font-family: 'Century Gothic';
font-weight: 100;
color: #0193b7;
}
ul{
list-style:none;
}
ul li:hover{
cursor:pointer;
color:#5bb12f;
}
#container {
border: 10px solid #293e6a;
padding: 0 0 20px 30px;
box-shadow: 0 0 5px 5px #c4c4c4;
}
p {
font-family: 'Eras ITC';
color: #e792b5;
font-size: 20px;
font-weight: normal;
}
.flyingButton {
position: fixed;
right: 18px;
top: 80px;
height: 50px;
width: 100px;
background: #293e6a;
border-radius: 25px 0 0 25px;
border: none;
color: #f2f2f2;
cursor:pointer;
}
.green{
color: #1B6F1B;
font-size: 18px;
}
.flyingButton:hover {
background: #0193b7;
}
.flyingButton:focus{
outline:0;
}
<body onload="ShowAllQues();">
<div id="container">
</div>
<input type="button" value="Answers" class="flyingButton" onclick="ShowAllAns();
return false;">

Categories

Resources