2013-04-20 138 views
-4

我有此代码,此代码必须能够计算用户的年龄,并且必须在提供的文本框中显示,并且如果用户更改其出生日期,则年龄必须更改。 但此代码不起作用,它不会在文本框中显示计算的年龄。使用Javascript的年龄计算器

<input name= "date" type="text" readonly="readonly" /> 

<select id="Ultra" onchange="run()"> 
<option value="11/15/991">1991-11-15</option> 
<option value="10/23/1992">1992-10-23</option> 
</select><br><br> 
TextBox1<br> 
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br> 
<script type="text/javascript"> 
function run() { 
    var birth = document.getElementById("Ultra").value; 
    var check = new Date(); 
    var milliDay = 1000 * 60 * 60 * 24; 

    var AgeinDay = (check - birth)/milliday; 
    var ComputAge = Math.floor(AgeinDay/365); 
    var age = ComputAge/365; 
    document.getElementById("srt").value = age; 
} 
</script> 
+0

对此不起作用的是什么? – sachleen 2013-04-20 23:52:26

+0

代码中有太多不必要的代码来计算年龄。 – 2013-04-20 23:53:05

+0

它不显示在文本框中的答案 – user2302009 2013-04-20 23:57:53

回答

0

试试这个..

function run() { 
    var birth = new Date(document.getElementById("Ultra").value); 
    var curr = new Date(); 
    var diff = curr.getTime() - birth.getTime(); 
    document.getElementById("srt").value = Math.floor(diff/(1000 * 60 * 60 * 24 * 365.25)); 
} 
0

有代码中的三个错误,请评论下面内嵌:

第一选项的年份值是991,而不是1991年,可能会引起你认为计算是错误的。

包含正在分配给出生变量的日期的字符串必须作为参数传递给Date()函数以创建可与当前日期对象一起使用的日期对象。

变量milliDay被声明,那么你试图使用milliday(错误的情况D)。

<input name= "date" type="text" readonly="readonly" /> 

<select id="Ultra" onchange="run()"> 
<option value="11/15/1991">1991-11-15</option> <!-- year value was 991 instead of 1991, might cause you to think the calculation is wrong --> 
<option value="10/23/1992">1992-10-23</option> 
</select><br><br> 
TextBox1<br> 
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br> 
<script type="text/javascript"> 
function run() { 
    var birth = new Date(document.getElementById("Ultra").value); //string containing date has to be passed as parameter to Date() function to create a date object that can be used with the current date object below 
    var check = new Date(); 
    var milliDay = 1000 * 60 * 60 * 24; 

    var AgeinDay = (check - birth)/milliDay; //variable here was milliday all small case, declared above as milliDay with a capital D 
    var ComputAge = Math.floor(AgeinDay/365); 
    var age = ComputAge/365; 
    document.getElementById("srt").value = age; 
} 
</script> 

这将返回假设第一个选项下面的值选择:

年龄:0.057534246575342465

ComputAge:21

你只是想获得的年龄里,或几个月,几个小时呢?

+0

我试图得到它在几年:) – user2302009 2013-04-21 00:33:26

+0

好吧,那么你只需要ComputAge变量,不需要除以365 :) – kais 2013-04-21 00:48:18