Ways to showcase array values on a calendar using javascript

Below is a piece of java script that creates a calendar based on the selected year and month:

document.write(makeCalendar(2013,0))
. The first parameter represents the year, while the second parameter indicates the month. I've managed to make it display calendar events for a specific day, but I'm having trouble getting it to show all the other dates stored in my HolidayName[] array. Even though I've written a loop to display all the events, it only shows the first date. The issue puzzles me as the loop should iterate through all the dates. Here's the loop along with the JavaScript code:

var HolidayName = new Array (0, 1, "New Years Day",6, 1, "Canada Day",11, 25, "Christmas Day",11, 26, "Boxing Day")
function getHoliday(month, day)
{
    for(var index = 0; HolidayName.length > index; index++)
    {
        if(HolidayName[index] == month && HolidayName[index+1] == day)
        {
            var name = HolidayName[index+2]
        }
        else
        {
            return ""
        }
        return name
    }
}   

The code snippet below showcases how the event is displayed in the "show dates" section using the getHoliday(mth, dayCtr) function:

function leapYear(yr) { 
if (yr < 1000) yr+=1900
return((yr%4 == 0) && ((yr%100 == 0) || (yr%400 ==0)))
}

function startCol(width, height, color){
return('<TD WIDTH=' + width + ' HEIGHT=' + height + '>' + '<FONT COLOR="' + color + '">');
}

function makeCalendar(yr, mth){

var months    = new Array("Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec")
var days      = new Array(31, leapYear(yr)?29:28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
var weekDays  = new Array("Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat")
var HolidayName = new Array (0, 1, "New Years Day",6, 1, "Canada Day",11, 25, "Christmas Day",11, 26, "Boxing Day")

function getHoliday(month, day)
{
    for(var index = 0; HolidayName.length > index; index++)
    {
        if(HolidayName[index] == month && HolidayName[index+1] == day)
        {
            var name = HolidayName[index+2]
        }
        else
        {
            return ""
        }
        return name
    }
}   

var mthSz         = days[mth]
var mthName       = months[mth]
var firstDyofMnth = new Date(yr, mth, 1)
var firstDay      = firstDyofMnth.getDay() + 1
var numRows       = Math.ceil((mthSz + firstDay-1)/7)
var mthNameHeight = 50

var borderWidth   = 2
var cellSpacing   = 4 
var cellHeight    = 80 

var hdrColor      = "midnightblue" 
var hdrSz         = "+3" 
var colWidth      = 100 

var dayCellHeight = 25 
var dayColor      = "black" 
var dayCtr    = 1


// Build the HTML Table 
var txt = '<CENTER>'
txt += '<TABLE BORDER=' + borderWidth + ' CELLSPACING=' + cellSpacing + '>' 

//Show Month Name and Year
txt += '<TH COLSPAN=7 HEIGHT=' + mthNameHeight + '>' 
txt += '<FONT COLOR="' + hdrColor + '" SIZE=' + hdrSz + '>' 
txt += mthName + ' ' + year + '</FONT>' + '</TH>'

// Show Days of the Week 
txt += '<TR ALIGN="center" VALIGN="center">'
for (var dy = 0; dy < 7; ++dy) {
    txt += startCol(colWidth, dayCellHeight, dayColor) + weekDays[dy] + '</FONT></TD>' 
}
txt += '</TR>'

// Show Dates in Calendar
for (var row=1; row <= numRows; ++row) {
    txt += '<TR ALIGN="right" VALIGN="top">'
    for (var col = 1; col <= 7; ++col) {
        if (((col < firstDay) && (row==1)) || (dayCtr>mthSz))
            {txt += '<TD BGCOLOR="Gainsboro"><BR></TD>'}
        else
            {
            txt += '<TD HEIGHT=' + cellHeight + '><FONT COLOR="' + dayColor + '"> <B>'
            txt += dayCtr 
            txt += '</B></FONT><BR>' + getHoliday(mth,dayCtr) + '</TD>'
            dayCtr++;
            }
    }
    txt += '</TR>'
}

// close all basic table tags and output txt string
txt += '</TABLE></CENTER>'
document.write(txt) 

}

Answer №1

Since you have else { return "" } followed by return name outside the if...else statement, the function will stop after its first run through the loop. It will return the name if the condition is true, or an empty string if false.

Furthermore, consider incrementing the index by 3 rather than 1 each time in the loop; remember to use semi-colons to terminate each line of code (except in {} blocks).

var HolidayName = new Array(0, 1, "New Years Day", 6, 1, "Canada Day", 11, 25, "Christmas Day", 11, 26, "Boxing Day");

function getHoliday(month, day) {
  for (var index = 0; index + 2 < HolidayName.length; index+=3) {
    if (HolidayName[index] == month && HolidayName[index + 1] == day) {
      return HolidayName[index + 2];
    }
  }
  return '';
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

Tips for ensuring all data is properly set before saving in mongoose

Struggling to update undefined or defined values in Mongoose due to the need to await their assignment. It seems like the code is not saving the data because USER.save() is executed before the values are set. How can I ensure that the data is updated/set ...

Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop? This is what I currently have: obj:{ a:3, c:5, d:1, g:15 } Basically, I want to achieve s ...

I seem to be having trouble getting Vue to recognize my components. Could it be that I am not registering them

I am currently working on developing a simple blog application using Laravel with Vue.js. I have successfully created custom components, registered them in my app.js file, and referenced them in the views by their component names. However, upon loading the ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

Creating responsive list items using Bootstrap 4 and Flexbox: Adjusting the width of <li> elements to fit within containers

Struggling with expanding li elements to match the container width? Despite tweaking individual widths and Flexbox properties, the desired outcome remains elusive. How can the width of each li be adjusted to align with the container, mirroring the dimensio ...

Tips for displaying an alert in the upcoming event loop

I recently started learning VueJS and decided to create a practice game to strengthen my understanding of the framework. http://jsfiddle.net/mzref4o0/1/ Within this game, the attack method is crucial in determining the winner: attack: function(isSpecial ...

Utilizing multiple criteria to filter through a nested array

I am faced with an array structured as follows const treeObj = [ { id: 1, name: 'Section One', items: [ { id: 1, name: 'Section One Item One' }, { id: 2, name: 'Section One Item Two' }, ...

Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

How can I deactivate all form controls within an AngularJS form?

To prevent any changes to the form components when the view button is clicked, I need to disable them. Here is my form: <form action="#" class="form-horizontal" > <div class="form-group"> <label for="fieldname" class="col-md-3 cont ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

The constricted styles are causing the whole page to bounce (scroll) up and down

On my SPA frontend, I have a parent div with a height of 580 containing 9 smaller divs (about 190px in height each). The parent div has an overflow set to hidden so that only 3 elements are visible at one time. Every 5 seconds, I change the styles by addin ...

Tips for sending data through AJAX before the browser is about to close

My issue is with a javascript function that I've called on the html unload event. It seems to be working fine in Google Chrome, but for some reason it's not functioning properly in Firefox and IE. <script> function fun() { ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...

I'm looking for an easy way to generate a special effect when my mouse interacts with a div using HTML, CSS, or JavaScript

I'm attempting to replicate this interesting effect where a div is surrounded by a container when the mouse hovers over it. It looks pretty cool, like in this image here: https://i.stack.imgur.com/p0epq.png Does anyone have any suggestions on how I ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

Ways to toggle the visibility of a div with a click event?

I am working on a project where I have a list view of items. I want to implement a feature where when a user clicks on an item, a hidden div below it will appear with options like price, quantity, and other details. I am looking for guidance on how to achi ...