Can somebody who knows javascript do a quick code check for me? I've been tuning this and I think it's correct, but just wanted to make sure because I've been staring at it for way too long.
This function takes a date of birth from a set of month, day, and year drop down fields, calculates the person's age, and then sets the value of an age field to the correct age.
Multiple people can be present on the page, so the function takes one argument, which is the person number of the individual being calculated (first person = 1, second person = 2, and so on).
Here it is:
Code:
function get_age(person_num)
{
var month_val = parseInt(document.getElementById('person_dob_month'+person_num).value, 10),
day_val = parseInt(document.getElementById('person_dob_day'+person_num).value, 10),
yr_val = parseInt(document.getElementById('person_dob_yr'+person_num).value, 10),
today_date,
today_year,
today_month,
today_day,
age;
if (day_val > 0 && month_val >= 0 && yr_val > 0) { // only calc if all fields selected
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - yr_val;
if (today_month === month_val) { // birthday is this month
if (today_day < day_val) { // birthday hasn't happened yet this month, subtract 1 from age
age--;
}
}
if (age < 0) { // Prevents age from being -1
age = '';
}
document.getElementById('person_age'+person_num).value = age;
}
}
Here is what the HTML fields look like (It all works fine, just wanted to include it so you can visualize better):
Code:
<select id="person_dob_month1" name="person_dob_month1">
<option value="-1"></option>
<option value="0">January</option>
...
<option value="11">December</option>
</select>
<select id="person_dob_day1" name="person_dob_day1">
<option value="0"></option>
<option value="1">1</option>
...
<option value="31">31</option>
</select>
<select id="person_dob_yr1" name="person_dob_yr1">
<option value="0"></option>
<option value="2012">2012</option>
...
<option value="1900">1900</option>
</select>