Triggering an event when a button is clicked in JavaScript

Currently, I have a JavaScript code that generates a grid of calendars based on the selected month and year. What I'm trying to achieve is to create a button that will trigger the display of these calendars.

UPDATED

Below is the code snippet:

<input type="number" name="a" id="month" />
<input type="number" name="a" id="year" />

<button type="button" class="btn btn-secondary" id ="clickMe">Button</button>

The issue I'm facing is that clicking the button does not lead to the display of the calendars. How can I modify the code to ensure that the calendars are shown only upon button click?

Answer №1

Many of the methods you are using seem to be incorrect, particularly those related to Date. It would be beneficial for you to refer to an updated and functional example.

(function myFunction() {
    function calendar(month, year) {
 
        var padding = "";
        var totalfeb = "";
        var i = 1;
        var current = new Date();
        var cmonth = current.getMonth();
        var day = current.getDate();
        var tempmonth = month + 1;
        var prevmonth = month - 1;

        if (month == 1) {
            if ((year % 100 !== 0) && (year % 4 === 0) || (year % 400 === 0)) {
                totalfeb = 29;
            } else {
                totalfeb = 28;
            }
        }

        var monthnames = ["jan", "feb", "march", "april", "may", "june", "july", "aug", "sept", "oct", "nov", "dec"];
        var daynames = ["sunday", "monday", "tuesday", "wednesday", "thrusday", "friday", "saturday"];
        var totaldays = ["31", "" + totalfeb + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];

        var tempdate = new Date(tempmonth + ' 1 ,' + year);
        var tempweekday = tempdate.getDay();
        var tempweekday2 = tempweekday;
        var dayamount = totaldays[month];

        while (tempweekday > 0) {
            padding += "<td class='premonth'></td>";
            tempweekday--;
        }

        while (i <= dayamount) {
            if (tempweekday2 > 6) {
                tempweekday2 = 0;
                padding += "</tr><tr>";
            }

            if (i == day && month == cmonth) {
                padding += "<td class='currentday'  onmouseover='this.style.background=\"#00ff00\"; this.style.color=\"#ffffff\"' onmouseout='this.style.background=\"#ffffff\"; this.style.color=\"#00ff00\"'>" + i + "</td>";
            } else {
                padding += "<td class='currentmonth' onmouseover='this.style.background=\"#00ff00\"' onmouseout='this.style.background=\"#ffffff\"'>" + i + "</td>";

            }

            tempweekday2++;
            i++;
        }

        var calendartable = "<table class='calendar'> <tr class='currentmonth'><th colspan='7'>" + monthnames[month] + " " + year + "</th></tr>";
        calendartable += "<tr class='weekdays'>  <td>sun</td>  <td>mon</td> <td>tues</td> <td>wed</td> <td>thurs</td> <td>fri</td> <td>sat</td> </tr>";
        calendartable += "<tr>";
        calendartable += padding;
        calendartable += "</tr></table>";
        document.getElementById("calendar").innerHTML += calendartable;

    }

    function displayCalendar() {
        for (i = 0; i < 12; i++) {
            calendar(i, 2020); 
        }
    }

  
    var el = document.getElementById("clickMe");
    if (el.addEventListener)
        el.addEventListener("click", displayCalendar, false);
    else if (el.attachEvent)
        el.attachEvent('onclick', displayCalendar);

})();
<button type="button" class="btn btn-secondary" id ="clickMe">Load Calendar</button>
<div id="calendar"/>

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

Retrieving PHP information using Javascript and storing it in an array

I have a PHP script that fetches data from a server and stores it in an array. I then convert this array into a JSON object using the following function: echo json_encode($result); Now I want to access this array in my JavaScript and display it. I want t ...

Creating HTML documents for an AngularJS application using the KeystoneJS content management system

As someone new to AngularJS and KeystoneJS, I am seeking guidance from the community. Any help offered would be greatly appreciated. Thank you all. I have successfully implemented a serving mechanism for my Angular application using Express's express ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Embedding JavaScript directly into text and executing it once the page has finished loading

Currently, I am dealing with an ASPx/C# page where clicking the Save button triggers a post back to the server. If the data in the controls already exists in the checked data stores, it is supposed to trigger an alert message. Previously, the developer uti ...

React not displaying wrapped div

I am facing an issue with my render() function where the outer div is not rendering, but the inner ReactComponent is displaying. Here is a snippet of my code: return( <div style={{background: "black"}}> <[ReactComponent]> ...

An error occurs with Three JS when trying to access a S3 Bucket used as a CDN due to Cross Origin

function displayItem() { startScene(); THREE.ImageUtils.crossOrigin = "anonymous"; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setTexturePath('https://cdn.rubyrealms.com/textures/'); mtlLoader.setPath('https://cdn.ru ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

Activate the Keypress event to update the input value in React upon pressing the Enter

I am facing an issue where I need to reset the value of an input using a method triggered by onPressEnter. Here is the input code: <Input type="text" placeholder="new account" onPressEnter={(event) => this.onCreateAccount(event)}> < ...

The combination of Protractor, Selenium, and Docker with Chrome results in a WebDriverError: an unknown issue occurred where Chrome failed to initiate

I followed the steps outlined in this tutorial http://www.protractortest.org/#/tutorial and https://github.com/angular/protractor-cookbook/tree/master/protractor-docker (I recently switched from using separate selenium hub and node to ) I have config ...

The significance of special characters when utilizing window.open

When attempting to open a URL in another tab using window.open, I encountered an issue with the single quotation mark. "javascript:if(w=window.open('https://wiki.abc.com/display/New%27s+Project'));"; The code renders the single quotati ...

What is the best way to update the wrapper when the iframe URL is modified?

On my webpage, there is an iframe that contains a form. I have a banner or header visible on the page as well. Once the user submits the form within the iframe, I would like the banner to disappear. To see an example of what I mean, you can visit This pa ...

Utilize the auto-complete feature to narrow down your options when filtering through a list

Check out this plunker that showcases a feature I am aiming to achieve. My goal is to implement an auto-complete list for users to filter the table. Currently, the filtering works smoothly while the user is typing. However, if the user selects an option ...

Steps for extracting a specific portion of a value contained within an attribute

In my code, there are multiple hyperlinks with different values attached to an onclick function. Here is an example: <a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a> <a onclick="Util ...

Error: JSON parsing error due to unexpected token C at the beginning of the string

When using ajax and json formatting, I am encountering this message. In PHP, the code array("message" => "Success", "data" => $data) is displayed successfully. However, it is not able to callback to ajax. How can I resolve this issue without deleting ...

What is the best way to implement validation for individual elements within an array that are being displayed on a webpage using a for loop?

Currently, I am utilizing Vue JS within the Vuetify framework to build a dynamic form: <v-text-field v-for="items in itemsArray" :key="items.id" v-model="items.data" :label="items.name" ></v-text-field> ...

Personalized sorting to match the unique rendering of cells in Material UI Data Grid

I have integrated the Material UI V4 Data Grid component into my React Js application. The Data Grid component requires two props: rows (list type) and columns (list type). Below is a sample row item: const rows = [ { id: 1, customerName: " ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

angular 2 checkbox for selecting multiple items at once

Issue I have been searching for solutions to my problem with no luck. I have a table containing multiple rows, each row having a checkbox. I am trying to implement a "select all" and "deselect all" functionality for these checkboxes. Below is an example o ...

Easiest homemade variations and pairings

Imagine having a basic array like ["apple", "banana", "lemon", "mango"];. For example, if we were to find the straightforward hand-rolled combinations of this array, selecting 3 items, but allowing for repetition: let array = ["apple", "banana", "lemon", ...