A little bit of everything…
RSS icon Home icon
  • Calculating age with JavaScript

    Posted on February 28th, 2009 Aleix No comments

    JavaScript LogoI’ve been working on a simple form – nothing really challenging – where members of a group can provide some data about themselves for registration purposes. However I tried adding an extra function to it: a small text field next to where they input their birth data, which displays their age (according of course to the birth date they provided).

    I thought therefore I could share this small piece of code so that other people wishing to add it to their websites can use it. The internet is already full of such scripts, but who knows, maybe someone finds it here and finds it useful…

    This script is reusable in as many fields as desired. The code is very simple: it receives three variables when the function is called, which are the ID of the birth date text field; the ID of the age field (output) and whether to alert if the age is under 18 (when set to ‘true’).

    The birth date must be in DD MM YYYY format (unless of course you modify the script code to accept other formats). The separators are irrelevant  for this script – unless you plan to save the date into a database as well – because the code only takes into account the integers with the JavaScript substring() method. So the date can be introduced like 19.05.1982, 19-05-1982, 19/05/1982, etc.

    The input format can be changed by modifying accordingly the following lines of code (and knowing how substring() works):

    
    var pyear = parseInt(input.substring(6,10));  // YYYY
    var pmonth = parseInt(input.substring(3,5)) - 1;   // MM
    var pday = parseInt(input.substring(0,2));  // DD
    

    CalendarJust one note here: see there’s a -1 in the pmonth variable value? This is because JavaScript month numbers are from 0 to 11 instead of 1 to 12. So without this -1, if a user would write 10 (October) as month of birth, JavaScript would believe it is 11 (November).

    The age is calculated once the user focuses out of the birth date text field, but you can change it to other events by altering the HTML code where the script is called. There’s no submit button either, but you can easily add one if you need to.


    Full script

    This is the full script with sample HTML included. You may customize it as you wish – especially the under 18 alert message.

    
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Age check</title>
    <script type="text/javascript">
    <!--
    function calculateAge(inputFieldId, outputFieldId, alert_18){
    
    var age;
    
    var input = document.getElementById(inputFieldId).value;
    
    // Past date info
    
    var pyear = parseInt(input.substring(6,10));
    var pmonth = parseInt(input.substring(3,5)) - 1;
    var pday = parseInt(input.substring(0,2));
    
    // Today info
    today = new Date();
    year = today.getFullYear() ;
    month = today.getMonth();
    day = today.getDate();
    
    if ( month < pmonth ){
    age = year - pyear - 1;
    }
    else if ( month > pmonth ){
    age = year - pyear;
    }
    else if ( month == pmonth ){
    if ( day < pday ){
    age = year - pyear - 1;
    }
    else if ( day > pday ){
    age = year - pyear;
    }
    else if ( day == pday ){
    age = year - pyear;
    }
    }
    document.getElementById(outputFieldId).value = age;
    
    if(alert_18 == 'true'){
    if(age < 18){
    
    //Customize alert message
    
    alert('Attention: under 18!');
    }
    }
    }
    //-->
    </script>
    
    </head>
    <body>
    
    <p>Hi! Please enter your date of birth...</p>
    
    <form>
    
    <input type="text" id="birthdate" size="10" onblur="calculateAge('birthdate','age','true')">
    
    <p style="font-size:8pt">
    
    (allowed formats: DD.MM.YYYY, DD/MM/YYYY, DD.MM.YYYY,etc)</p>
    <p>Your age:
    
    <input type="text" id="age" size="2" disabled="disabled"> </p>
    
    </form>
    
    </body>
    </html>
    

    For your information, there are no validation methods here. So it is possible to introduce dates in a wrong format or future dates. I’ve not thought of writing a validation script for it, so take it as it is or leave it…

    You can try a working example of the script above here.

    Leave a reply