Sum days on input date

Asked

Viewed 2,640 times

6

I have a input date type, I would like to add to it 7 days and put this value in another input also date type, I tried to do so:

<script>
$('#txtSolicitacao').on('blur', function(){
    data = $('#txtSolicitacao').val() + 7 ; 
    $('#txtTermino').val(data);
});
</script>

Note: the date is in the American format year-month-day.

2 answers

4


I suppose this is what you’re looking for.

    $('#txtSolicitacao')[0].valueAsDate = new Date();

    $('#txtSolicitacao').change(function() {
      var date = this.valueAsDate;
      date.setDate(date.getDate() + 7);
      $('#txtTermino')[0].valueAsDate = date;
    });

    $('#txtSolicitacao').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="date" id="txtSolicitacao">
<br>
<input type="date" id="txtTermino">

1

taking into account that input[type='date'] stores the date in ISO format, you can do the following:

unfortunately the code below will only get friendly in Chromium based browsers, but the logic to add 7 days remains the same.

var dataInicio = document.getElementById("dataInicio");
var dataFinal = document.getElementById("dataFinal");

dataInicio.addEventListener("focusout", function (event) {
  var offset = new Date().getTimezoneOffset();
  var data = new Date(dataInicio.value);
  data.setMinutes(data.getMinutes() + offset);
  data.setDate(data.getDate() + 7);

  dataFinal.value = data.toISOString().substring(0, 10);
})

var event = new Event("focusout");
dataInicio.dispatchEvent(event);
<div>
  <label>
    Data Inicio: 
    <input id="dataInicio" type="date" value="2016-02-26" />
  </label>
</div>
<div>
  <label>
    Data Final: 
    <input id="dataFinal" type="date" />
  </label>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.