Display Days In A Week Using JavaScript

In this tutorial we will create a Display Days In A Week using JavaScript. This code will display a days in a week when user submit the form input. The code use onclick() to call a function that will display a list of arrays that consist of days using for loop to loop through the index position of arrays in a form of weekdays. This a free program feel free to modify it and use it in your system. JavaScript is a scripting or programming language that allows you to implement complex things on web pages. It is widely used in designing a stunning website. It is an interpreted programming language that has a capabilities of Object-Oriented.

Getting started:

This is the link for the bootstrap that has been used for the layout of the calculator https://getbootstrap.com/.

The Main Interface

This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.

Display Days Of A Week Using JavaScript Source Code



Creating the Main Function

This code contains the main function of the application. This code will display a days in a week when the button is clicked. To do this just copy and write these block of codes as shown below inside the text editor then save it as script.js inside the js folder.
  1. function calculateWeek(date){
  2.     var days = new Array();
  3.     for (var i = 0; i < 7; i++){
  4.         days[i] = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 1 + i);
  5.     }
  6.        
  7.     return days;
  8. }
  9.  
  10. function getDays(){
  11.         var date = document.getElementById('date');
  12.         if(date.value == ""){
  13.                 alert("Please enter a date first!");
  14.         }else{
  15.                 var months= ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  16.                 var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  17.                 var newDate = new Date(date.value);
  18.                 var dates = new Array();
  19.                 dates = calculateWeek(newDate);
  20.                 var data ="<h2 class='alert-info'>Weeks of "+date.value+"</h2>";
  21.                 for(var i=0; i < dates.length; i++){
  22.                         data += "<label>"+days[dates[i].getDay()]+": <span class='text-info'>"+months[dates[i].getMonth()]+" "+dates[i].getDate()+", "+dates[i].getFullYear()+"</span></label><br />";
  23.                 }
  24.                
  25.                 document.getElementById('result').innerHTML = data;
  26.         }
  27. }
There you have it we successfully created a Display Days In A Week using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Tags

Add new comment