Search code examples
javascripthtmldateinput

set the end date based on start date in the html input field using js


set the difference between start date and end date of 20 months and automatically update in the end date input field. Using only javascript if possible the more details refer to the above one

<!DOCTYPE html>
<html lang="en">
   <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Set Date Input Value from Another Date Input</title>
  </head>
  <body>
    <label for="sourceDate">Source Date:</label>
    <input type="date" id="sourceDate" />
    <br /><br />
    <label for="targetDate">Target Date:</label>
    <input type="date" id="targetDate" />

   <script>
      // Wait until the DOM is fully loaded
      document.addEventListener("DOMContentLoaded", function () {
    

      // Select the input elements
      var sourceDateElement = document.getElementById("sourceDate");
      var targetDateElement = document.getElementById("targetDate");

      // Add event listener to the source date input
      sourceDateElement.addEventListener("change", function () {
      

      // Get the value from the source date input
      var sourceDateValue = sourceDateElement.value;
      const d = new Date(sourceDateValue);
      const d2 = new Date(d);
      //   const d3= new Date(d2)
      d2.setMonth(d2.getMonth() + 20);
      console.log(d2);

      // Set the value to the target date input
      targetDateElement.value = d2;
    });
  });
    </script>
  </body>
</html>

Solution

  • you need to break the date to year, month and day and then set the date element

          document.addEventListener("DOMContentLoaded", function () {
        
            var sourceDateElement = document.getElementById("sourceDate");
            var targetDateElement = document.getElementById("targetDate");
    
            sourceDateElement.addEventListener("change", function () {
              
              var sourceDateValue = sourceDateElement.value;
              
              if (sourceDateValue) {
                const d = new Date(sourceDateValue);
                const d2 = new Date(d);
                
                // add 20 months
                d2.setMonth(d2.getMonth() + 20);
                
                var year = d2.getFullYear();
                var month = ('0' + (d2.getMonth() + 1)).slice(-2); // add 1 to the month 0-indexed
                var day = ('0' + d2.getDate()).slice(-2);
    
                targetDateElement.value = `${year}-${month}-${day}`;
              }
            });
          });
     <label for="sourceDate">Source Date:</label>
        <input type="date" id="sourceDate" />
        <br /><br />
        <label for="targetDate">Target Date:</label>
        <input type="date" id="targetDate" />