I recommend using .change
on top of the drop with the number of months.
You have the string with the starting date, you can create a Date()
with this string ... and from there add the number of months.
Of course, you will also need a date formation, which I would advise:
function formatarData(data) {
var d = new Date(data),
mes = '' + (d.getMonth() + 1),
dia = '' + d.getDate(),
ano = d.getFullYear();
if (mes.length < 2) mes = '0' + mes;
if (dia.length < 2) dia = '0' + dia;
return [dia, mes, ano].join('/');
}
That is, with your input:
var qtdMeses = 6;
var dtInicio = new Date($("#dataInicio").val());
dtInicio.setMonth(dtInicio.getMonth() + qtdMeses); //adicionando meses
$("#dataTermino").val(formatarData(dtInicio));
EDIT :
dtInicio
also has to be formatted before it is used ... I updated its assignment as follows:
var dtInicio = new Date(formatarData($("#dataInicio").val()));
Online sample
OTHER EDIT:
As I said in the comments, I think the best solution is to add N days (since, on January 30 if I add + 1 month, it will return NaN
, since there is no February 30th ... So, I prepared another Online Example and made a change in the structure of the events. I created a function to calculate the date ... . This function is called every time the change()
event of the number of months dropdown is "triggado"
and every time the start date field loses focus ( blur
).
$("#meses").change(function() {
calcularDataTermino();
});
$("#dataInicio").blur(function() {
calcularDataTermino();
});
function calcularDataTermino() {
var qtdMeses = parseInt($("#meses").val());
var qtdDias = 30 * parseInt($("#meses").val()); // sempre 30 dias + de acordo com a quantidade de meses: 1 mês = +30 dias; 2 meses = + 60 dias; 3 meses = 90 dias;
var dtInicio = new Date(formatarData($("#dataInicio").val()));
//dtInicio.setMonth(dtInicio.getMonth() + qtdMeses); //+ N qtdMeses
dtInicio.setDate(dtInicio.getDate() + qtdDias); //+ N dias
$("#dataTermino").val(formatarData(dtInicio));
}