AidenFive
AidenFive

Reputation: 39

how to get a date from a date input using javascript

hello so i have a javascript function that takes two dates from two date inputs, compares them and returns a boolean value except it doesn't work

function checkdate() {

	var datefrom = new Date();
	var dateto = new Date();


	datefrom = getElementById("date_from").innerHTML;
	dateto = getElementById("date_to").innerHTML;

	if (datefrom > dateto) {
		alert("Dateto must be bigger than datefrom  ");

		return false;
	} else return true;

}
<form onsubmit="return checkdate()" class="forms-sample" method="post"
   action="addstage.php">
   <div class="form-group row">
      <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Date
      Début</label>
      <div class="col-sm-9">
         <input type="date" class="form-control"
            id="date_from" placeholder="Debut" name="datedebut"  required="required">
      </div>
   </div>
   <div class="form-group row">
      <label for="exampleInputEmail2" class="col-sm-3 col-form-label">Date
      Fin</label>
      <div class="col-sm-9">
         <input type="date" class="form-control"
            id="date_to" placeholder="Fin" name="datefin" required="required">
      </div>
   </div>
   <div class="form-check form-check-flat form-check-primary"></div>
   <button type="submit" class="btn btn-primary mr-2" value="addStage"
      name="action">Add</button>
</form>

Upvotes: 1

Views: 1434

Answers (2)

David
David

Reputation: 219096

Two problems:

  1. You're calling getElementById globally, but should be calling it on the document object.
  2. You're using .innerHtml instead of .value

As an aside you also don't need to create new Date() objects just to throw them away. Simply set the values you want right away:

var datefrom = document.getElementById("date_from").value;
var dateto = document.getElementById("date_to").value;

Note: These values are strings, not dates. According to MDN:

The displayed date format will differ from the actual value — the displayed date is formatted based on the locale of the user's browser, but the parsed value is always formatted yyyy-mm-dd.

So for comparison purposes this should still work, since yyyy-mm-dd is an incrementing value. But if you need a Date object then MDN also says there's a .valueAsDate property (though has no example on that page), as well as a .valueAsNumber which returns a UNIX timestamp that should be reliable for creating a Date.

Otherwise dates can be tricky in JavaScript, and libraries like Moment.js exist to make that easier.

Upvotes: 3

Gh05d
Gh05d

Reputation: 9002

You can't use getElementById as a static method. You have to call it on document:

datefrom= document.getElementById("date_from").innerHTML;
dateto= document.getElementById("date_to").innerHTML;

Upvotes: 0

Related Questions