这是我在StackOverflow上的第一篇文章, 我在这个网站上已经阅读了很多关于代码片段的页面,并且总能提供很好的答案和建议..
现在我需要一些帮助.. 我想填充多个输入字段,我尝试在JavaScript中添加字段ID,但到目前为止还没有运气。
<script type="text/javascript">
<!--
function calculateAge(inputFieldId, outputFieldId, alert_18){
var age;
var input = document.getElementById(inputFieldId).value;
// Past date info
var pyear = parseInt(input.substring(6,10));
var pmonth = parseInt(input.substring(0,2)) - 1;
var pday = parseInt(input.substring(3,5));
// Today info
today = new Date();
year = today.getFullYear() ;
month = today.getMonth();
day = today.getDate();
if ( month < pmonth ){
age = year - pyear - 1;
}
else if ( month > pmonth ){
age = year - pyear;
}
else if ( month == pmonth ){
if ( day < pday ){
age = year - pyear - 1;
}
else if ( day > pday ){
age = year - pyear;
}
else if ( day == pday ){
age = year - pyear;
}
}
document.getElementById(outputFieldId).value = age;
document.getElementById(outputFieldId).value = age2;
if(alert_18 == 'true'){
if(age < 18){
//Customize alert message
alert('Attention: under 18!');
}
}
}
//-->
</script>
任何帮助都会非常感激
答案 0 :(得分:0)
我建议使用以下解决方案来处理人口到任意数量的输出域(并粗略计算年龄 - 不考虑闰年):
<script type="text/javascript">
<!--
function calculateAge(inputFieldId, outputFieldId, alert_18){
var input = document.getElementById(inputFieldId).value,
pyear = parseInt(input.substring(6,10)),
pmonth = parseInt(input.substring(0,2)) - 1,
pday = parseInt(input.substring(3,5)),
dt1 = new Date(),
dt2 = new Date(pyear, pmonth, pday),
ageMs = dt2.getTime() - dt1.getTime(),
age = parseInt(ageMs / 1000 / 60 / 60 / 24 / 365);
if(outputFieldId instanceof Array) {
for(var i = 0, l = outputFieldId.length; i < l; i++)
document.getElementById(outputFieldId[i]).value = age;
}
else
document.getElementById(outputFieldId).value = age;
if(alert_18 && age < 18) {
//Customize alert message
alert('Attention: under 18!');
}
}
//-->
</script>
然后当你调用它时,你可以传递一个字符串作为outputfieldid,如下所示:
calculateAge("get-age", "calculated-age", true);
或者您可以传递一系列像这样的字段:
calculateAge("get-age", ["calculated-age1", "calculated-age2"], true);