Grace Grace - 1 month ago 17
HTML Question

Converting HTML form input into Javascript variables and comparing values

I am trying to compare the birth dates of two people. Person 1 and Person 2 input their names and dates of birth in an HTML form, and I want to use Javascript to compare the two dates and print out which person is older on the HTML page. However, I'm not sure how to submit the form and compare the dates. Here is what I have so far for the HTML:

<form id="form1">
Full name of first person: <input type="text" name="name1"><br>
Birthday: <input type="date" date="date1"><br>
<br>
Full name of second person: <input type="text" name="name2"><br>
Birthday: <input type="date" date="date2"><br>
</form>


And the Javascript:

var name1 = document.getElementsByName("name1");
var name2 = document.getElementsByName("name2");
var date1 = document.getElementsByName("date1");
var date2 = document.getElementsByName("date2");


How do I submit the variables in HTML and then have Javascript compare the two dates?

Answer

You forgot two things:

  1. A submit button.
  2. A submit handler.

I guess this solves your question.

window.onload = function () {
  document.getElementById("form1").onsubmit = function () {
    var name1 = document.getElementById("name1");
    var name2 = document.getElementById("name2");
    var date1 = document.getElementById("date1");
    var date2 = document.getElementById("date2");
    if ((new Date(date1.value)).getTime() < (new Date(date2.value)).getTime())
      console.log(name1.value + " is greater than " + name2.value);
    else
      console.log(name2.value + " is greater than " + name1.value);
  };
};
<form id="form1">
  Full name of first person: <input type="text" id="name1"><br>
  Birthday: <input type="date" id="date1"><br>
  <br>
  Full name of second person: <input type="text" id="name2"><br>
  Birthday: <input type="date" id="date2"><br>
  <input type="submit" value="Check" />
</form>