2013-04-20 178 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