0

function submit(){
  var date1=input[type="date"];
  var date2=console.log(Date());
  var Datediff= date2 - date1
  alert(Datediff)
}
<form onsubmit="submit">
<input type="date" />
<input type="submit" />
</form>

As u can see im a begginer. Tried doing everything by myself, but nothing worked, need help.

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
The senix
  • 11
  • 2

2 Answers2

2
  • You have to return false on submit event to prevent page reload
  • You have to give an ID to your date input to get his value
  • You have to create date with date constructors
  • You have to convert in unit you want to display (days, month...)

function alertDayDiff() {
    var input = document.getElementById('date');
    var date1 = new Date(input.value);
    var date2 = new Date();
    var timediff = Math.abs(date2 - date1);
    var daydiff = Math.floor(timediff / (1000 * 3600 * 24));
    alert(daydiff);
}
<form onsubmit="alertDayDiff(); return false;">
    <input type="date" id="date" />
    <input type="submit" />
</form>
alex
  • 5,661
  • 6
  • 33
  • 54
0

Your syntax is a mess... You need to learn the basics first, then try to do something basic that works.

First of all in your form event you need to call the function inserting the parentesis: <form onsubmit="submit()">, but apparently "submit" is a reserved word, so you need to use other function name.

This line is completely wrong: var date1=input[type="date"];

This is also wrong, as console.log does not return a value to "date2": var date2=console.log(Date()); and Date() is not what you want. You need a new instance of date: "new Date()"

I made some fixes in the example below. Compare each line with your code and see the syntax differences:

function validateForm() {
  var date1 = document.querySelector('#myDate').valueAsDate;
  var date2 = new Date();
  
  console.log('date1', date1);
  console.log('date2', date2);
  
  var dateDiff = date2 - date1;

  console.log('dateDiff ', dateDiff );
  alert(dateDiff);
  
  return false;
}
<form onsubmit="return validateForm()">
  <input type="date" id="myDate" />
  <button type="submit">Submit</button>
</form>
clayton.carmo
  • 121
  • 1
  • 4