Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript从html字段获取年龄_Javascript_Html - Fatal编程技术网

使用Javascript从html字段获取年龄

使用Javascript从html字段获取年龄,javascript,html,Javascript,Html,我需要弹出一个对话框来显示输入值的年龄(以年和月为单位)。我试过好几种方法,但还是不行。我得到了NaN的答案。有人能帮我吗 我的html: <label for="dob">Child’s Date of birth</label> <input class="form-control" type="date" name"dob" placeholder="Date of birth" id="dob" onblur"dateofBirth()"/> 我猜d

我需要弹出一个对话框来显示输入值的年龄(以年和月为单位)。我试过好几种方法,但还是不行。我得到了NaN的答案。有人能帮我吗

我的html:

<label for="dob">Child’s Date of birth</label>
<input class="form-control" type="date" name"dob" placeholder="Date of birth" id="dob" onblur"dateofBirth()"/>

我猜dofBirth是输入之后的字符串类型。你需要把它变成一个日期,它才能作为一个日期工作

var age = (new Date - new Date(dofBirth))

希望有帮助

首先,日期输入法还没有得到广泛支持,尽管如此,chrome给我的值是“2014-11-05”

因此,您可以使用badrequest400的方法,但似乎有一个时区调整。因此,我建议如下:

var tempStr = doBirth.split("-");
var age = (new Date() - new Date(tempStr[0], tempStr[1] - 1, tempStr[2])); // Plus your other calculations.

由于月份从0到11,所以负1是必要的

dofBirth
有什么值(提示:这取决于您在输入中键入的内容)。当您试图从
新日期
中减去它时,您预计会发生什么情况?它是否应该是
警报(“孩子的年龄是”+年龄)@mornenel。。。那只是一个疏忽。我打字很快,发完帖子一分钟后就收到了回复。需要更多帮助吗&
var tempStr = doBirth.split("-");
var age = (new Date() - new Date(tempStr[0], tempStr[1] - 1, tempStr[2])); // Plus your other calculations.