"use strict";
window.onload = function() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() 1;
var yyyy = date.getFullYear();
//Add a zero if one Digit (eg: 05,09)
if (dd < 10) {
dd = "0" dd;
}
//Add a zero if one Digit (eg: 05,09)
if (mm < 10) {
mm = "0" mm;
}
minYear = yyyy - 80; //Calculate Minimun Age (<80)
maxYear = yyyy - 18; //Calculate Maximum Age (>18)
var min = minYear "-" mm "-" dd;
var max = maxYear "-" mm "-" dd;
document.getElementById("start").setAttribute("min", min);
document.getElementById("start").setAttribute("max", max);
};
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="trip-start" value="2021-10-02" />
What specifically doesn't work is my JS code. My HTML works fine but my JS code, which is responsible for restricting the date which can be inputted in order to ensure that the inputter is within ages 18-80 at the time of filling out the form.
Thank you.
CodePudding user response:
You can shorten your code by using setFullYear to get the date and toISOString().slice(0, 10) get the right format
<html>
<head>
<script>
window.onload = function() {
const today = new Date();
const today18YearsAgo = new Date(today.setFullYear(today.getFullYear() - 18));
const today80YearsAgo = new Date(today.setFullYear(today.getFullYear() - 80));
document.getElementById("start").setAttribute("min", today80YearsAgo.toISOString().slice(0, 10));
document.getElementById("start").setAttribute("max", today18YearsAgo.toISOString().slice(0, 10));
}
</script>
</head>
<body>
<input type="date" id="start" required="required" name="trip-start" />
</body>
</html>
CodePudding user response:
Your code is correct , just you have not defined the variables minYear
maxYear
to correct that write var
before these where they are first used .
I have written var
where before minYear
maxYear
where they are first time used . Here is demo
"use strict";
window.onload = function() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() 1;
var yyyy = date.getFullYear();
//Add a zero if one Digit (eg: 05,09)
if (dd < 10) {
dd = "0" dd;
}
//Add a zero if one Digit (eg: 05,09)
if (mm < 10) {
mm = "0" mm;
}
var minYear = yyyy - 80; //Calculate Minimun Age (<80)
var maxYear = yyyy - 18; //Calculate Maximum Age (>18)
var min = minYear "-" mm "-" dd;
var max = maxYear "-" mm "-" dd;
document.getElementById("start").setAttribute("min", min);
document.getElementById("start").setAttribute("max", max);
};
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="trip-start" value="2021-10-02" />