Search code examples
javascriptdate

input a week, submit input and get all days in that week each in its own paragraph


I'd like users to to input a date, e.g '16 nov 2023', and get all dates in that specific week starting from monday which would return as example:

13 nov 2023
14 nov 2023
15 nov 2023
16 nov 2023
17 nov 2023
18 nov 2023
19 nov 2023

However I can't get around a way to bind then with my HTML page such that there's an input field where user enters a date and there's a submit button where upon selecting the dates are retrieved and displayed on the page each in its own paragraph tag.

This is the code I have but I'm failing to bind it with my page:

function days(current) {
  var week = [];
  // Starting Monday not Sunday 
  var first = current.getDate() - current.getDay() + 1;
  current.setDate(first);
  for (var i = 0; i < 7; i++) {
    week.push(new Date(+current));
    current.setDate(current.getDate()+1);
  }
  return week;
}

var input = document.getElementById('date').innerHTML = new Date(2023, 05, 13);
console.log('input: %s', input);
var result = document.getElementById('date1').innerHTML = days(input);
<input id="date" placeholder="type">
<button type="button" onclick="days()">press me</button>

Solution

  • To bind events to actions within the HTML you can use addEventListener(). In this case I would suggest listening for the input event of a date input. You can then take the value the user has chosen and pass it to your days() method to build the array of dates that you require.

    From there you can create a HTML string to output each date in its own <p> tag which you can display within a container element, like this:

    const outputContainer = document.querySelector('#output-container');
    
    function getDaysOfWeek(current) {
      var week = [];
      var first = current.getDate() - current.getDay() + 1;
      current.setDate(first);
      for (var i = 0; i < 7; i++) {
        week.push(new Date(+current));
        current.setDate(current.getDate() + 1);
      }
      return week;
    }
    
    document.querySelector('#date').addEventListener('input', e => {
      const weekDates = getDaysOfWeek(new Date(e.target.value));
      const html = weekDates.map(d => `<p>${d.toLocaleString()}</p>`).join('');
      outputContainer.innerHTML = html;
    });
    p { margin: 0; }
    <input type="date" id="date" placeholder="type" />
    
    <div id="output-container"></div>

    Note that I used toLocaleString() to format the dates using the culture set in your browser. This can easily be updated to output the date in whatever format you require.