Adding number of days to current date in Javascript dynamically

Posted by : Leo T Abraham on 8 August, 2013

Here what we are doing is: Setting curent date to a textbox and making it readonly. Then we allow user to enter the number of days to be added to the current date. On change event, the number of  days entered is added to the current date. Try out the following code to see its working.

             <title>Adding number of days to current date in Javascript</title>
       <body onload="addDate();">
            <h1>Adding number of days to current date in Javascript</h1>
            Today's Date (MM / DD / YYYY) : <input type="text" id="date1" readonly/> <br/> <br/>
            Number of days to add : <input type="text" id="days" onChange="datechange()" /> <br/> <br/>
            New Date (MM / DD / YYYY) : <input type="text" id="date2"
            <script type="text/javascript">
                  function datechange()
                        var d = document.getElementById('days').value;
                        var myDate = new Date(document.getElementById('date1').value);
                        myDate.setDate(myDate.getDate() + parseInt(d));
                        document.getElementById('date2').value = (myDate.getMonth() + 1) + '/' + (myDate.getDate()) + '/' + (myDate.getFullYear());
                  function addDate()
                         date = new Date();
                         var month = date.getMonth()+1;
                         var day = date.getDate();
                         var year = date.getFullYear();
                         if (document.getElementById('date1').value == '')
                               document.getElementById('date1').value = day + '/' + month + '/' + year;

user image
great !