Skip to content Skip to sidebar Skip to footer

Dynamically Add One Year To Input Type Month Based On Another Input Type Month Using Javascript

I have two input type of month. What I want to happen is when I input a date to the first field, the second field will automatically be filled with the same month and a year ahead.

Solution 1:

Following is the code through which you can get your required purpose

<script>functiongetDateAhead()
{
    var str = document.getElementById('fromDate').value;
    var res = str.split("-");
    var newdate = (parseInt(res[0])+1)+"-"+res[1]
    console.log(str);
    console.log(newdate);
    document.getElementById('toDate').value = newdate;
}
</script><inputtype="month"id="fromDate"onChange="getDateAhead()"/><inputtype="month"id="toDate"/>

Update

<script>functiongetDateAhead()
{
    var str = document.getElementById('fromDate').value;
    var res = str.split("-");
var year = parseInt(res[0])+1;    
var month = parseInt(res[1])-1;
    if (month <= 9 && month > 0 )
    {
        month = "0"+month;
    }
    elseif (month == 0)
    {
        month = "12";  
        year = year - 1;
    }
    var newdate = year+"-"+month;
    console.log(str);
    console.log(newdate);
    document.getElementById('toDate').value = newdate;
}
</script><inputtype="month"id="fromDate"onChange="getDateAhead()"/><inputtype="month"id="toDate"/>

Working Demo

Solution 2:

This JS uses the date object to calculate the deadline. The deadline date is always the last day of the previous month in the next year. deadline contains a full date object with the deadline date for further using.

document.getElementsByName('fromDate')[0].addEventListener('change', function (e) {
    var fromDate = newDate(e.target.value);
    var deadline = newDate(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate()-1);
    document.getElementsByName('deadline')[0].value = deadline.getFullYear() + '-' + ((deadline.getMonth()+1).toString().length < 2 ? '0' + (deadline.getMonth()+1).toString() : deadline.getMonth()+1);
});

JSfiddle

Post a Comment for "Dynamically Add One Year To Input Type Month Based On Another Input Type Month Using Javascript"