Drop down calendar in Javascript

I am in the process of developing a virtual JavaScript calendar dropdown feature. I aim to have the correct number of days displayed upon selecting a month, but currently, no days appear when I make a selection. Can someone please assist me with this issue? I must avoid using jQuery again as I risk losing my job this time.

<html>
<head>
<script type="text/javascript">
function show(x) {
var mon = document.getElementById(x).innerHTML;
//if month value is nothing display no days
if (mon == "") {
    for(i=1; i < 32; i++) {
        document.getElementById("day" + i).style.display="none";
    }
} else if ((mon == "January") || (mon == "March") || (mon == "May") || (mon == "July") || (mon == "August") || (mon == "October") || (mon == "December")) {
    for(i=1; i < 32; i++) {
        document.getElementById("day" + i).style.display="";
    }
} else if ((mon == "April") || (mon == "June") || (mon == "September") || (mon == "November")) {
    for(i=1; i < 31; i++) {
        document.getElementById("day" + i).style.display="";
    }
} else {
    for(i=1; i < 30; i++) {
        document.getElementById("day" + i).style.display="";
    }
}
}
</script>

</head>

<body>
Calendar<br>
<hr align="left" width="200px"/>


--Year ------ Month ----- Day<br>

<select name="year">
<option value="defaulty"></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>

<select name="month" onchange="show(this.value)">
<option id="defaultm" value="defaultm"></option>
<option id="January" value="January">January</option>
<option id="February" value="February">February</option>
<option id="March" value="March">March</option>
<option id="April" value="April">April</option>
<option id="May" value="May">May</option>
<option id="June" value="June">June</option>
<option id="July" value="July">July</option>
<option id="August" value="August">August</option>
<option id="September" value="September">September</option>
<option id="October" value="October">October</option>
<option id="November" value="November">November</option>
<option id="December" value="December">December</option>
</select>

<select name="day">
<option id="defaultd" value="defaultd"></option>
for(i=1; i < 32; i++) {
    <option id="day" + i value="day" + i style="display:none">i</option>
}
</select>



</body>

</html>

Answer №1

Let's delve into some meaningful discussion with this comment: Take a look at this jQuery-free PURE JS solution.

I opted for this approach because 1) I'm not fond of writing HTML, and 2) I want to showcase the importance of mastering Javascript skills.

Keep in mind that there may be compatibility issues with certain browsers (especially older IE versions), so you'll need to address those independently.

html:

<div id="calendar-container"></div>

js:

(function() {
    var calendar = [
        ["January", 31],
        ["February", 28],
        ["March", 31],
        ["April", 30],
        ["May", 31],
        ["June", 30],
        ["July", 31],
        ["August", 31],
        ["September", 30],
        ["October", 31],
        ["November", 30],
        ["December", 31]
        ],
        cont = document.getElementById('calendar-container');

    var sel_year = document.createElement('select'),
        sel_month = document.createElement('select'),
        sel_day = document.createElement('select');

    function createOption(txt, val) {
        var option = document.createElement('option');
        option.value = val;
        option.appendChild(document.createTextNode(txt));
        return option;
    }

    function clearChildren(ele) {
        while (ele.hasChildNodes()) {
            ele.removeChild(ele.lastChild);
        }
    }

    function recalculateDays() {
        var month_index = sel_month.value,
            df = document.createDocumentFragment();
        for (var i = 0, l = calendar[month_index][1]; i < l; i++) {
            df.appendChild(createOption(i + 1, i));
        }
        clearChildren(sel_day);
        sel_day.appendChild(df);
    }

    function generateMonths() {
        var df = document.createDocumentFragment();
        calendar.forEach(function(info, i) {
            df.appendChild(createOption(info[0], i));
        });
        clearChildren(sel_month);
        sel_month.appendChild(df);
    }

    sel_month.onchange = recalculateDays;

    generateMonths();
    recalculateDays();

    cont.appendChild(sel_year);
    cont.appendChild(sel_month);
    cont.appendChild(sel_day);
}());​

Check out the jsFiddle Demo for more details.

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

The test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

Issue with Jquery Drag and Drop functionality, navigate to a different page

I am trying to incorporate a page with js from quotemedia.com using Jquery. When I insert the js into the sortable, and then drag and drop the element containing the js, it suddenly switches to full page display. This issue occurs in Firefox, but IE works ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

Build a photo carousel similar to a YouTube channel

Is there a way to create an image slider similar to the one on YouTube channels? I've noticed that when there are multiple videos on a channel, YouTube displays them in a slider with back and forth buttons to navigate through the videos that aren&apos ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

the event listener for xmlhttprequest on load is not functioning as expected

I am facing an issue with validating a form using JavaScript and XMLHttpRequest. The onload function is supposed to display an alert, but it only works sometimes. I'm struggling to identify my mistake. document.getElementById("button").addEventListen ...

Tips for replicating input boxes in a while loop

HTML : <table> <tr> <td> <input type="text" name="name[]" value=" echo $ail"> <label >Address</label> <input type="text" name="countryname[]" id='countryname_1 ...

Is it possible to make API calls within the componentWillMount lifecycle method in React?

I've been immersed in the world of React for the past year. The standard practice within my team is to make an API call in componentDidMount, fetch the data, and then setState after receiving the data. This ensures that the component has fully mounted ...

Unlimited scrolling feature on a pre-filled div container

Looking for a way to implement infinite scroll on a div with a large amount of data but struggling to find the right solution? I've tried various jQuery scripts like JScroll, MetaFizzy Infinite Scroll, and more that I found through Google search. Whi ...

The issue of JavaScript failing to connect to the HTML file

As I work on my basic HTML file to learn Javascript, I believed that the script was correctly written and placed. Nevertheless, upon loading the file in a browser, none of the script seems to be functioning. All of my javascript code is external. The follo ...

The response from a jQuery ajax call to an MVC action method returned empty

I am working on an inventory application with the following layout: <body> <div class="container" style="width: 100%"> <div id="header"> blahblahblah </div> <div class="row"> <div id="rendermenu ...

Using Selenium and Python to showcase the source of an image within an iframe

My goal is to automatically download an image from shapeNet using Python and selenium. I have made progress, but I am stuck on the final step. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s ...

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

Convert several XML nodes to display in an HTML format

I am currently facing an issue where I am trying to display all the nodes of a specific tag in XML. Although it does filter the data correctly, only one node is showing up. Is there anyone who can assist me with this problem? Below is the XML content: < ...

explore a nested named view using ui-router

My app has a view called mainContent. <div class = "wrapper" ui-view = "mainContent"> </div> There is only one route for this view. $stateProvider .state("home", { url: "/home", vi ...

Date selection feature in Material UI causing application malfunction when using defaultValue attribute with Typescript

Recently, I discovered the amazing functionality of the Material UI library and decided to try out their date pickers. Everything seemed fine at first, but now I'm facing an issue that has left me puzzled. Below is a snippet of my code (which closely ...