我有一个带有“日期”元素和提交按钮的HTML表单。有2个功能。一种是在“ date” HTML元素中根据给定的出生日期计算年龄。另一个功能是将年龄与最小允许年龄进行比较。我需要帮助来完成它。在代码注释中查看我的问题。是的,我看到了其他类似的问题。我想学习,而不仅仅是复制/粘贴。如果我了解自己的代码/语法有什么问题,那么我会学得更好。提前致谢。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var minAge = 18;
var curDate = new Date();
var curr_year = curDate.getFullYear();
var curr_month = curDate.getMonth();
//Calculates age from given Birth Date in the form//
function _calcAge() {
var dt1 = document.getElementById('date').value;
var birth_date = new Date(dt1);
var birth_year = birth_date.getFullYear();
var birth_month = birth_date.getMonth();
var calc_year = curr_year - birth_year;
var calc_month = curr_month - birth_month;
//The following below is what I am not sure about.
//I need to combine years and months and
//convert them into a string??? Is this syntax dead wrong?
var final_result = (calc_year && "." && calc_month).toString();
// final result should be a number with a decimal point, example: 35.5
final_result = parseFloat;
return (final_result);
alert(final_result);
}
//Compares calculated age with minimum age and acts according to rules//
function _setAge() {
var age = _calcAge();
//alert("my age is " + age);
if (age < minAge) {
alert("You are not allowed into the site. The minimum age is 18!");
} else
alert("Welcome to my Site");
window.open(main.htm, _self);
}
</script>
<form>
Date Of Birth: <input type="date" name="date of birth" id="date" />
<input type="submit" name="submit" id="submit" onClick="_setAge();" />
</form>
</body>
</html>
我设法使它起作用。信用也去https://stackoverflow.com/users/444991/matt因为我向他借这里的一部分:https://stackoverflow.com/a/4076440/3189118
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var minAge = 18;
var today = new Date()
//Calculates age from given Birth Date in the form//
function _calcAge(birthDate, givenDate) {
givenDate = new Date(today);
var dt1 = document.getElementById('date').value;
var birthDate = new Date(dt1);
var years = (givenDate.getFullYear() - birthDate.getFullYear());
if (givenDate.getMonth() < birthDate.getMonth() ||
givenDate.getMonth() == birthDate.getMonth() && givenDate.getDate() < birthDate.getDate()) {
years--;
}
return years;
}
//Compares calculated age with minimum age and acts according to rules//
function _setAge() {
var age = _calcAge();
if (age < minAge) {
alert("You are not allowed into the site. The minimum age is 18!");
} else
alert("Welcome to my Site");
}
</script>
<form>
Date Of Birth: <input type="date" name="date of birth" id="date" />
<input type="submit" name="submit" id="submit" onClick="_setAge();" />
</form>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句