So I'm trying to reset a date if the input date is today or in the past, just wondering why doesn't date = "" work since I already declared the variable "date" earlier, but I found that it works if I type document.getElementById("date").value = ""; instead, when (I presume) they're the same thing?
function validate_date() {
// convert to Date objects to compare
var date = document.getElementById("date").value;
var date_object = new Date(date)
var today = new Date();
if (date_object <= today) {
alert("Date cannot be today or the past!");
// document.getElementById("date").value = "";
date = ""; //doesn't reset
}
}
<input type="date" name="date" id="date" onblur="validate_date();">
If you need to use inline JS pass in the event to the function, then pick up the value from that. Then you can reset the value. This way you don't need an id on the input.
function validate_date(e) {
var date = e.value;
var date_object = new Date(date);
var today = new Date();
if (date_object <= today) {
alert("Date cannot be today or the past!");
e.value = '';
}
}
<input type="date" onblur="validate_date(this);">
when directly selecting an attribute of a DOM element, the variable becomes an independent entity.
By selecting the element instead will allow access to change its attributes.
function validate_date() {
var date = document.getElementById("date");
date.value = "";
}
<input type="date" name="date" id="date" onblur="validate_date();">