I recommend using the .change
on top of the drop with the amount of months.
If you have the string with the initial date, you can create a Date()
with this string...and from there add up the amount of months.
And of course, you will also need a date formation, which I advise this:
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 entrance:
var qtdMeses = 6;
var dtInicio = new Date($("#dataInicio").val());
dtInicio.setMonth(dtInicio.getMonth() + qtdMeses); //adicionando meses
$("#dataTermino").val(formatarData(dtInicio));
EDIT:
to dtInicio
also has to be formatted before being used... I updated the attribution of it as follows:
var dtInicio = new Date(formatarData($("#dataInicio").val()));
Online example
ANOTHER EDIT:
As I mentioned in the comments, I find the best solution to add N days (since, on January 30 if I add + 1 month, will return NaN
, for there is no February 30th... So I have prepared another Online Example and made a change in the structure of events. I created a function to make the date calculation.... this function is called every time the event change()
Quantity of months dropdown for "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));
}
what is the calculation formula? what do you want to calculate? You can give an output example?
– Marllon Nasser
Sure! An example: 03/28/2016 + 6 months = 09/28/2016 (not exactly, considering months with 30 or 31 days)
– Hebert Richard