当我输入输入字段中的值时,我想查找此人是否少于18岁。为此,我创建了一个日期输入框并创建了一个函数。我的功能无法正常工作。我做错了什么,我该怎样才能做到这一点?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Birthday Validation</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#DOB").on("change paste keyup", function() {
$datestring = $(this).val();
//alert(jQuery.type(Date($datestring)));
//$eightYearsAgo = now() - $birthday;
$birthday = $.datepicker.formatDate('yy/mm/dd', new Date()) - Date($datestring);
if(!birthday.isValid()){
alert("INVALID DATE");
}else if (eightYearsAgo.isAfter(birthday)){
alert("18+");
}else{
alert("< 18");
}
});
});
</script>
</head>
<body>
<input name="DOB" type="date" class="form-control" id="DOB" required placeholder="MM/DD/YYYY" onchange="validate(date)">
</body>
</html>
答案 0 :(得分:4)
我已经完成了这项工作,您需要使用正确的datePicker
功能才能使其正常运行。
这是代码:
$(document).ready(function () {
$("#age").datepicker({
onSelect: function(value, ui) {
var current = new Date().getTime(),
dateSelect = new Date(value).getTime();
age = current - dateSelect;
ageGet = Math.floor(age / 1000 / 60 / 60 / 24 / 365.25); // age / ms / sec / min / hour / days in a year
if(ageGet < 18){
less_than_18(ageGet);
}else{
greater_than_18(ageGet);
}
},
yearRange: '1900:+0d',//base year:current year
changeMonth: true,
changeYear: true,
defaultDate: '-18yr',
}).attr("readonly", "readonly"); //prevent manual changes
function less_than_18(theAge){
alert("Failed! your age is less than 18. Age: "+theAge);
}
function greater_than_18(theAge){
alert("Done! your age is greater or equal to 18. Age: "+theAge);
}
});
您可以在此处测试:https://jsfiddle.net/h4ppstrf/