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

Creating seamless scrolling in ReactJS without any pre-built components

Can anyone guide me on how to implement an infinite scroll in reactJs using a JSON dataset? I prefer building it from scratch without relying on any library. {data?.map((conto) => { return ( <Suspense key={conto._uid} fallback={<p>Loadin ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

Using JSON objects effectively in MVC4, including parsing them seamlessly!

I am struggling with understanding how to effectively utilize JSON objects within MVC and the correct way to pass them from Controller, to View, to Jscript. I am also unsure if I am correctly parsing the JSON objects at the appropriate places... Within m ...

Challenges in using Three.js on mobile devices with orientation capabilities

I'm currently running tests on a web application built using three.js, and it seems that users on tablets, especially Android devices, are experiencing some unusual behavior within the scene. https://i.sstatic.net/FkFi3.jpg Below is how the view sho ...

Comparing a stored array in Mongo against a native JavaScript array with identical length and values results in a failed deep assert comparison

In my mongoose ORM, I have a field in mongo defined as: state: {type: [Number], required: true } When I check a sample document in the mongo console, the state appears as: state: [ 1, 1, 1 ] Everything seems to be in order so far. However, when I try t ...

AngularJS: intercepting custom 404 errors - handling responses containing URLs

Within my application, I have implemented an interceptor to handle any HTTP response errors. Here is a snippet of how it looks: var response = function(response) { if(response.config.url.indexOf('?page=') > -1) { skipException = true; ...

Step-by-step guide on achieving a radiant glow effect using React Native

I am looking to add a glowing animation effect to both my button and image elements in React Native. Is there a specific animation technique or library that can help achieve this effect? While I have this CSS style for the glow effect, I am uncertain if ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

Whenever I try to launch my React app using the `npm start` command in my command

After successfully creating a Simple React App and getting the happy hacking message on cmd, I encountered numerous errors when trying to run "npm start" on cmd. Despite multiple attempts at uninstalling and reinstalling node and npm, the issue persists. H ...

Update the CSS for InputLabel

I have a drop-down list that I want to customize. The issue is illustrated below: I'm looking to center the text "choose format" within the field and adjust the font size. return ( <FormControl sx={{ m: 1, minWidth: 150 }} size="sm ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

React-select allows for multiple selections within a component when the onChange function

I am currently utilizing react-select. Per the official documentation, it recommends using 'isMulti' to select more than one option. Below is the custom component that I have created. import React from 'react'; import { Form } from &ap ...

Jquery Autocomplete has the ability to store and recall previous user selections

When the region is selected, autocomplete addresses should be displayed. Each time the region changes, the Jquery autocomplete function is called. While I am able to get the correct autocomplete addresses for the current region, I also receive address list ...

Why is the value of the select element in AngularJS an object?

Here is a JSON object: { "9000A": { "LOCname":"A Place", "LOCid":"9000A" }, "2700C": { "LOCname":"C Place", "LOCid":"2700C" }, "7600B": { "LOCname":"B Place", "LOCid":"7600B" } } To ...

What's the reason behind the malfunction of this code on Chrome?

After recently installing Mobiscroll, I have been using the date scroller feature with the following code to manage the textbox. <script type="text/javascript"> $(function() { // create a datepicker with default settings $("#begi ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

There seems to be an issue with the integration of Bootstrap in my JavaScript file

Is there a way to ensure that each new data entry in the array appears next to each other rather than stacking beneath one another? This is a JavaScript file with HTML written in Bootstrap format. const collegeData = [{ name: "University of Penn ...

Utilize jQuery and JSP (or PHP) to showcase detailed information about a specific item when a user clicks on it within an HTML page

For my upcoming college project, I am tasked with developing a movie library. The main page of the library will feature various movie posters. Upon clicking on a poster, users will be directed to a dedicated page displaying detailed information about the ...

What is the best situation to utilize $(document).ready()?

After observing that using $(document).ready(..) seems to introduce a noticeable delay in applying JavaScript effects, I've been contemplating the best approach. I know that simply placing the effect in a <script> tag may not work if the DOM isn ...