如何使用html&从输入类型“日期"中获取“年龄"js? [英] How to get the 'age' from input type 'date' using html & js?

查看:43
本文介绍了如何使用html&从输入类型“日期"中获取“年龄"js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何使用Javascript从日期输入类型中获取年龄,并以HTML格式显示.

My question is how to get the age from the date input type using Javascript, and show it in Html.

我希望用户能够从日期输入类型中选择其出生日期,然后将其放入"bday" ID中,我可以然后使用来计算年龄并填写"resultBday"元素ID.

I want the user to be able to select his Date of Birth from the Date input type, which should then be put into the 'bday' ID that I can then use to calculate the age from and fill it in the 'resultBday' element ID.

例如:
当用户选择"1990年1月15日"时,我希望它在innerHtml中显示"24岁".

For example:
When the user selects 'January 15th, 1990' I want it to show "24 years old" in the innerHtml.

这是我目前拥有的:

HTML:

<p id="resultBday"></p>
<input type="date" name="bday" id="bday" onchange="submitBday()">

JS:

function submitBday () {
    var Q4A = "Your birthday is: "
    var Bday = document.getElementById('bday').value;
    Q4A += Bday;

    var theBday = document.getElementById('resultBday');
    theBday.innerHTML = Q4A;
}

推荐答案

function submitBday() {
    var Q4A = "Your birthday is: ";
    var Bdate = document.getElementById('bday').value;
    var Bday = +new Date(Bdate);
    Q4A += Bdate + ". You are " + ~~ ((Date.now() - Bday) / (31557600000));
    var theBday = document.getElementById('resultBday');
    theBday.innerHTML = Q4A;
}

jsFiddle示例

这篇关于如何使用html&amp;从输入类型“日期"中获取“年龄"js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆