使用Javascript在文本更改事件上计算年龄 [英] Calculate Age using Javascript on text Change event
本文介绍了使用Javascript在文本更改事件上计算年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hai,
我有一个Ajax datepicker扩展器,带有一个Textbox,可以在我的aspx页面中选择出生日期。我想在有人输入或选择上述文本框中的日期时计算年龄,并将其显示在标签中。我用Google搜索了一下。但我无法得到一个完美的。我在服务器端完成了它。但为了避免回发,我希望它在客户端本身完成。我的日期时间格式是dd-MMM-yyyy..
请帮帮我...
谢谢。
Hai,
I have a Ajax datepicker extender with a Textbox to select Date of Birth in my aspx page. I want to calculate Age when some one enter or select a date in the above mentioned textbox and should display it in a label. I googled it. But I couldnt get a perfect one. I have done it in server side. But to avoid postback I want it to be done in the client side itself. My datetime format is "dd-MMM-yyyy"..
Please help me...
Thank you.
推荐答案
您需要创建一个简单的日期差异函数;见这里的例子。 http://ditio.net/2010/05/02/javascript-date-difference-calculation / [ ^ ]
从控件中读取值,获取当前日期,并进行计算..........
You need to create a simple date diff function; See examples here. http://ditio.net/2010/05/02/javascript-date-difference-calculation/[^]
Read the value from the control, get the current date, and do the calc..........
javascript函数下面将从2个日期值计算年龄。请记住日期值应为DD / MM / YYYY格式。
Below javascript function will calculate age from 2 date values. Remember date values should be in DD/MM/YYYY format.
function CalculateAge(TodaysDate,NewDate) // Pass date in DD/MM/YYYY Format
{
var day1 = parseInt(TodaysDate.substring(0,2),10);
var mon1 = parseInt(TodaysDate.substring(3,5),10);
var yr1 = parseInt(TodaysDate.substring(6,10),10);
var day2 = parseInt(NewDate.substring(0,2),10);
var mon2 = parseInt(NewDate.substring(3,5),10);
var yr2 = parseInt(NewDate.substring(6,10),10);
var diff1 = parseInt(yr1 - yr2);
var diff2 = parseInt(mon1 - mon2);
var diff3 = parseInt(day1 - day2);
if(diff2 <0)
{
diff1 = diff1-1;
diff2 = diff2+12;
}
if(diff3 <0)
{
diff2 = diff2-1;
if(diff2<0)
{
diff1 = diff1-1;
diff2 = diff2+12;
}
}
var strAge = diff1+"."+diff2;
return parseFloat(strAge);
}
这篇关于使用Javascript在文本更改事件上计算年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文