Grand Marshal Braev
Grand Marshal Braev

Reputation: 283

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. How can I achieve this using javascript? Thank you.

Start date: <input type='month' name='fromdate'> to <input type='month' name='deadline'>

Note: I need to use input type month, and please don't recommend to me that I use jquery's datepicker because it uses textbox.

Upvotes: 1

Views: 1732

Answers (2)

alexP
alexP

Reputation: 3765

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 = new Date(e.target.value);
    var deadline = new Date(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

Upvotes: 1

Blu
Blu

Reputation: 4056

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

<script>
function getDateAhead()
{
    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>
<input type="month" id="fromDate" onChange="getDateAhead()"/>
<input type="month" id="toDate"/>

Update

<script>
function getDateAhead()
{
    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;
    }
    else if (month == 0)
    {
        month = "12";  
        year = year - 1;
    }
    var newdate = year+"-"+month;
    console.log(str);
    console.log(newdate);
    document.getElementById('toDate').value = newdate;
}
</script>
<input type="month" id="fromDate" onChange="getDateAhead()"/>
<input type="month" id="toDate"/>

Working Demo

Upvotes: 1

Related Questions