Reputation: 39
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
Reputation: 219096
Two problems:
getElementById
globally, but should be calling it on the document
object..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