0

I have an html form that has a "date created" date input, a "number of months" number input, and a "due date" read only date input.

Basically what I want to do is when the user initializes the value of "date created" and then proceeds to change the value of the "number of months", the "due date" will automatically calculate for itself the moment the user changes the "number of months".

Any solution will be of great help. Thanks very much!

P.S. if its important, I will be using a php script to send these values to a mysql server.

sukaretto
  • 59
  • 1
  • 7

1 Answers1

0

Try something like this below using vanilla JS:

let dateCreated = document.getElementById("date-created");
let amtOfMonths = document.getElementById("amt-of-months");
let dueDateInput = document.getElementById("due-date");

dateCreated.onchange = function() {updateDueDate()};
amtOfMonths.onchange = function() {updateDueDate()};

function updateDueDate() {
  if (dateCreated.value && amtOfMonths.value) {
    let dueDate = addMonths(dateCreated.value, amtOfMonths.value);
    dueDateInput.value = dueDate.toLocaleDateString('en-CA');
  }
}

function addMonths(date, months) {
    let newDate = new Date(date);
    var day = newDate.getDate();
    newDate.setMonth(newDate.getMonth() + +months);
    if (newDate.getDate() != day)
        newDate.setDate(0);
    return newDate;
}
<label for="date-created">Date created</label><br>
<input type="date" name="date-created" id="date-created"><br><br>


<label for="amt-of-months">Amount of months</label><br>
<input type="number" name="amt-of-months" id="amt-of-months"><br><br>

<label for="due-date">Due date</label><br>
<input type="date" name="due-date" id="due-date">

In this example, I'm adding an onchange function to the dateCreated and amtOfMonths inputs. Inside the function, I'm checking if both these inputs have values. If both inputs have values, then the addMonths function is called to calculate the dueDate, and it sets it to the dueDateInput.

As for sending to your server via PHP, you can do this in a onsubmit function attached to the form element containing your inputs.

Jeith
  • 395
  • 2
  • 11