Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected.

Here's the content of my HTML page:

<!doctype html>
<html>
<head>
<title>Document</title>
</head>
<body>

  <h1>Practice</h1>
  <button id="btn" onclick="printDate()">Print Date</button>
  <p id="Day"></p>
  <button onclick="printTime()"> Show Clock </btn>
  </br>
  <p id="Time"></p>
  <script src="Clock.js"></script>

</body>
</html>

In clock.js, you'll find the following code:

// This is where the function is defined

function printDate() {

// Retrieving values from the "Date" object using different methods

   var date = new Date();
   var day = date.getDay();
   var dateNum = date.getDate();
   var month = date.getMonth();
   var year = date.getYear();

// Adjusting for JS year format

   year += 1900

// Changing the numerical value of "day" to the actual day name string

   switch(day){

case 0: day = "Sunday"
break;
case 1: day = "Monday"
break;
case 2: day = "Tuesday"
break;
case 3: day = "Wednesday"
break;
case 4: day = "Thursday"
break;
case 5: day = "Friday"
break;
case 6: day = "Saturday"
break;
}

// Changing the numerical value of "month" to the actual month name string

   switch(month){

case 0: month = "January"
break;
case 1: month = "February"
break;
case 2: month = "March"
break;
case 3: month = "April"
break;
case 4: month = "May"
break;
case 5: month = "June"
break;
case 6: month = "July"
break;
case 7: month = "August"
break;
case 8: month = "September"
break;
case 9: month = "October"
break;
case 10: month = "November"
break;
case 11: month = "December"
break;
}

// Displaying the values in the p tag with ID "Day"

document.getElementById("Day").innerHTML = "Today is: "+day+" the "+dateNum+" of "+month+", "+year

}

function printTime() {

document.getElementById("Time").innerHTML = "Current Time"

}

I apologize for all the comments; they're helping me learn.

Now, onto the issue - when I try to call printTime() in the HTML document, it doesn't work and doesn't replace the innerHTML with "Current Time." However, the other function works perfectly fine. What could be causing this discrepancy? Why does the first function work but not the second?

Any assistance would be greatly appreciated!

Answer №1

The button you are using has a wrong closing tag. Instead of </btn>, it should be </button>.

Answer №2

just making a few tweaks to your code

var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthsOfYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

function displayDate() {
    var currentDate = new Date();
    var dayOfMonth = currentDate.getDate();   
    var dayOfWeek = daysOfWeek[currentDate.getDay()];
    var currentMonth = monthsOfYear[currentDate.getMonth()];
    var currentYear = currentDate.getFullYear();

    document.getElementById("Day").innerHTML = "Today is: "+dayOfWeek+" the "+dayOfMonth+" of "+currentMonth+", "+currentYear;
}

function displayTime() {
    document.getElementById("Time").innerHTML = "Current Time"
}

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 maxBodySize feature is ineffective in restify

I am currently running a node app on version v0.10.33 with the Restify module ^2.8.3 installed. var app = restify.createServer(); app.use(restify.queryParser()); app.use(restify.bodyParser({ maxBodySize: 1, //Issue: The limit is not being enforced at th ...

Sending data through forms

I'm having trouble storing values input through a dropdown menu in variables event1 and event2, despite trying global declarations. How can I successfully store a value to both variables and pass it to the JavaScript code? Thank you. <!DOCTYPE HT ...

Display or conceal div elements using JavaScript

Is there a way to hide certain divs when clicking on a specific div box? Clicking on the box will trigger the hiding of some application divs. See the first image below: When the boxes are hidden, the other divs will readjust in place of the current divs ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Error Encountered: unable to perform function on empty array

I've encountered an issue with my Vue JS 2.6.10 application after updating all packages via npm. Strangely, the app works perfectly fine in development environment but fails to function in production. The error message displayed is: Uncaught TypeErr ...

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...

The personalized directive does not respond to modifications in attributes

I am in the process of creating a modal directive that will be used to display data tables. The directive has an attribute called modal-visible, which is initially set to false by default. If this value is true, the modal will be visible when loaded. Howev ...

Tips for integrating AngularJS into Zend Framework 2

Hi there! I am a newcomer to Zend Framework 2 and I am exploring the integration of AngularJS into my project. Currently, I am calling a function in the controller like this: return new ViewModel(array( 'result' => $result, 'use ...

Having trouble getting "Hello World" to display in ReactJS

I can't seem to get "hello world" as the output in my code. It's a simple code, but I'm getting a different result when using the createElement function. I'm still new to react and could use some help. Here is the code: <!DOCTYPE h ...

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

Issue with timebox filtering in customapp.js for Rally SDK 2

I am interested in creating a timebox filtered app and found an example at However, when attempting to run this on a custom HTML page, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) on th ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Error encountered in Bootstrap 5: Popper__namespace.createPopper function is not defined

Currently using Django to host web pages. Focus is on enabling offline access by downloading all necessary resources to ensure webpage functionality, like Bootstrap 5. Attempting to utilize the dropdown menu feature in Bootstrap: Dropdowns depend o ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...

Before installing npm packages, ensure to gracefully stop the process during pre-installation

Is there a way to stop the npm install process conditionally within a preinstall script? At the moment, I have a preinstall script named preinstall.js: if (someCondition) { process.kill(process.ppid, 'SIGKILL'); } The content of my package.js ...

You can interact with our dropdown menu using the tab key, even when it is

We are looking to make our dropdown tabbable when expanded and non-tabbable when collapsed. We attempted using tabindex="-1" on the content inside the expandable div, but this resulted in it being non-tabbable even when expanded. Any suggestions on how t ...

Building a search form using Vue.js with query parameters

Incorporating Vue.js 2.6 with the vue-router component has been quite a journey for me. My search form setup looks like this: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class= ...

After the form is submitted, attach a div containing the saved record

Once the form is submitted, I'd like to seamlessly add the newly saved record to my existing div that holds all the records. If there's a better method for accomplishing this, please let me know. I'm unsure of the correct approach to achiev ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

What is the best way to display a component with multiple pieces of content?

I have a tool that generates card components, extracting data from a const array and displaying it in a table format within a card UI component. I am looking to add an ADD button inside each card to open a modal with input fields. However, the issue is tha ...