manuel antunes
manuel antunes

Reputation: 26

Javascript add year to date and put in html input

In a view, I have a date that the user must enter. What I want is that the other dates are automatically filled in with +2 years for one and +5 years for another.

Thank you for your help.

html

<input type="date" th:field="*{date_fabrication}" class="form-control 
    col-xs-3 col" id="fabId"
        th:onblur="majdates()"
        th:errorclass="invalid"
        th:placeholder="#{fabricationEquipment}"
        style="width: 200px;font-size:12px;"
        required>

function

<script>
    function majdates() {
        var recupDate = document.getElementById("fabId").value;
        var plusTwoYears = recupDate.setFullYear(date.getFullYear() + 2);
        document.getElementById("commissioningId").value = plusTwoYears;

    }
</script>

edit : the target date :

<input type="date" th:field="*{date_mise_en_service}" class="form-control col"
    id="commissioningId"
    th:errorclass="invalid"
    th:placeholder="#{commissioningEquipment}"
    style="width: 200px;font-size:12px;">

thanks to Rory, the solution below

<script>

document.querySelector('#fabId').addEventListener('blur', e => {
    var recupDate = new Date(e.target.value);
    var plusTwoYears = new 
Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
    var formatedPlusTowYears =plusTwoYears.toISOString().slice(0,10);
    document.querySelector("#commissioningId").value = formatedPlusTowYears;
    document.querySelector("#volumeId").value = formatedPlusTowYears;
});
</script>

Upvotes: 1

Views: 1207

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your code is almost there. The main issue is that recupDate will be a string. You need to parse it to a Date object in order to call setFullYear on it.

Also note that the result of setFullYear() will be an epoch timestamp, not a date, so you'll again need to parse the response of that to a Date object - and possibly format it manually depending on the output required.

document.querySelector('#fabId').addEventListener('blur', e => {
  var recupDate = new Date(e.target.value);  
  var plusTwoYears = new Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
  document.querySelector("#commissioningId").value = plusTwoYears;
});
input {
  width: 200px;
  font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" class="form-control col-xs-3 col" id="fabId" required />

<input type="text" readonly id="commissioningId" />

Finally, I also changed the logic to use an unobtrusive event handler instead of the onblur attribute, as the latter are no longer good practice.

Upvotes: 3

Related Questions