locked
Unable to get property of undefined or null reference in Contact Form RRS feed

  • Question


  • function CalculateAge() {
    
        if (Xrm.Page.getAttribute("birthdate") != null) {
            var birthdate = Xrm.Page.getAttribute("birthdate").getValue();
            //  today's date
            var new_age = new Date();
            // if the supplied date is before the birthdate return
            if (new_age < birthdate) {
                if (Xrm.Page.getAttribute("new_age") != null)
                    Xrm.Page.getAttribute("new_age").setValue(null);
    
                 return;
    
             }
            var age = new_age.getFullYear() - birthdate.getFullYear();
            if (birthdate.getMonth() > new_age.getMonth() || (birthdate.getMonth() == new_age.getMonth() && birthdate.getDate() > new_age.getDate())) { age--; }
    
            if (Xrm.Page.getAttribute("new_age") != null)
                Xrm.Page.getAttribute("new_age").setValue(age);
        }
    }

    OK, so this ALMOST works - everything looks good while working with contacts that have something in for "birthdate"

    however, if there is no value for birthdate i get the following error:

    Is there a way to either skip this error or somehow handle a blank birthdate field? I thought the "if (Xrm.Page.getAttribute("birthdate") != null) {" automatically ignored any fields where birthdate actually does equal null?


    Tuesday, September 23, 2014 9:24 PM

All replies

  • Hi Daniel,

    Use the code below:

    function CalculateAge() {

        if (Xrm.Page.getAttribute("birthdate").getValue() != null) {
            var birthdate = Xrm.Page.getAttribute("birthdate").getValue();
            //  today's date
            var new_age = new Date();
            // if the supplied date is before the birthdate return
            if (new_age < birthdate) {
                if (Xrm.Page.getAttribute("new_age").getValue() != null)
                    Xrm.Page.getAttribute("new_age").setValue(null);

                 return;

             }
            var age = new_age.getFullYear() - birthdate.getFullYear();
            if (birthdate.getMonth() > new_age.getMonth() || (birthdate.getMonth() == new_age.getMonth() && birthdate.getDate() > new_age.getDate())) { age--; }

                Xrm.Page.getAttribute("new_age").setValue(age);
        }
    }
    Saad


    • Edited by Mohd Saad Wednesday, September 24, 2014 5:14 AM
    Wednesday, September 24, 2014 5:13 AM
  • Hi Daniel,

    You should have both the conditions. If field is not added on form then it will throw an error. 

    So Xrm.Page.getAttribute("birthdate") will check if field is added on form and Xrm.Page.getAttribute("birthdate").getValue() will check it contains value.

     if (Xrm.Page.getAttribute("birthdate") != null && Xrm.Page.getAttribute("birthdate").getValue() != null) {

    }

    Thanks!
    Wednesday, September 24, 2014 5:37 AM