JavaScript: Issue with Calculating Age from Date of Birth in Form Data and display age on text field

I’m trying to calculate the age based on a date of birth (DOB) input in a form using JavaScript. I’ve set up a form where users can input their first name, last name, gender, and DOB. The DOB should be used to calculate the age, which is then displayed in the form. It is a multi step form

the first step of the from here is the code


<div class="col-lg-2 mb-4">
                                                    <div class="form-group">
                                                        <label class="text-label">First Name*</label>
                                                        <input type="text" name="firstName" class="form-control " placeholder="FirstName"  >
                                                    </div>
                                                  </div>
                                                  
                                                 <div class="col-lg-2 mb-4">
                                                    <div class="form-group">
                                                        <label class="text-label">Last Name*</label>
                                                        <input type="text" name="lastName" class="form-control" placeholder="LastName" >
                                                    </div>
                                                 </div>



div class="form-group col-md-3">
                                                    <div class="form-group">
                                                        <label class="text-label">Date of Birth*</label>
                                                        <input type="text" name="dob" class=" form-control" placeholder="DateOfBirth" id="mdate-3">
                                                    </div>
                                                </div>


<div class="row"> <!-- 3rd row -->
                                                    <!-- drop dowwn with gender -->
                                                    <div class="form-group col-md-3">
                                                    <label>Select Gender*</label>
                                                    <select class="form-control" id="inputState" name="Gender" >
                                                    <option selected disabled>Choose...</option>
                                                    <option value="Male">Male</option>
                                                    <option value="Female">Female</option>
                                                    </select>
                                                    </div>


    <div class="form-group">
                                                        <label class="text-label">Number of Adults*</label>
                                                        <input type="number" name="numberofAdults" id = "numberofAdults" min ="0"   class="form-control" onchange="addAdultFields()" required>
                                                    </div>
                                                </div>

here is the javascript

// Define a global object to hold form data
var formData = {
  firstName: '',
  lastName: '',
  gender: '',
  dob: ''
};

// Function to save form data
function saveFormData() {
  const firstNameInput = document.querySelector('input[name="firstName"]');
  const lastNameInput = document.querySelector('input[name="lastName"]');
  const genderSelect = document.querySelector('select[name="Gender"]');
  const dobInput = document.querySelector('input[name="dob"]');

  if (firstNameInput) formData.firstName = firstNameInput.value;
  if (lastNameInput) formData.lastName = lastNameInput.value;
  if (genderSelect) formData.gender = genderSelect.value;
  if (dobInput) formData.dob = dobInput.value;

  console.log('Data saved to formData:', formData);
}

// Add event listeners
document.addEventListener('DOMContentLoaded', function() {
  const firstNameInput = document.querySelector('input[name="firstName"]');
  const lastNameInput = document.querySelector('input[name="lastName"]');
  const genderSelect = document.querySelector('select[name="Gender"]');
  const dobInput = document.querySelector('input[name="dob"]');

  if (firstNameInput) firstNameInput.addEventListener('input', saveFormData);
  if (lastNameInput) lastNameInput.addEventListener('input', saveFormData);
  if (genderSelect) genderSelect.addEventListener('change', saveFormData);
  if (dobInput) dobInput.addEventListener('input', saveFormData);
});

// Function to calculate age based on date of birth
function calculateAge(dob) {
  console.log('Calculating age for dob:', dob); // Debugging line
  if (!dob) {
    console.log('DOB is empty');
    return '';
  }
  const birthDate = new Date(dob);
  console.log('Parsed birthDate:', birthDate); // Debugging line
  if (isNaN(birthDate.getTime())) {
    console.log('Invalid date of birth:', dob); // Debugging line
    return '';
  }
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDifference = today.getMonth() - birthDate.getMonth();
  if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  console.log('Calculated age:', age); // Debugging line
  return age;
}

function addAdultFields() {
  var numAdults = parseInt(document.getElementById("numberofAdults").value, 10);
  var parent = document.getElementById("adultFormcontainer");

  // Clear existing form fields
  parent.innerHTML = '';

  for (var i = 0; i < numAdults; i++) {
    var fieldset = document.createElement("fieldset");
    fieldset.style.display = "flex";
    fieldset.style.flexDirection = "row";
    fieldset.style.marginBottom = '100px';
    fieldset.style.paddingTop = '5px';
    fieldset.classList.add("float-left");

    var legend = document.createElement("legend");
    legend.textContent = i === 0 ? "Head of Household" : "Adult " + i;
    fieldset.appendChild(legend);

    var fields = [
      { label: "First Name", name: i === 0 ? "firstName" : "adult" + i + "FirstName", type: "text", value: i === 0 ? formData.firstName : "" },
      { label: "Last Name", name: i === 0 ? "lastName" : "adult" + i + "LastName", type: "text", value: i === 0 ? formData.lastName : "" },
      { label: "Gender", name: i === 0 ? "gender" : "adult" + i + "Gender", type: "select", options: ["Male", "Female"], selected: i === 0 ? formData.gender : "" },
      { label: "Age", name: "age", type: "text", value: i === 0 ? calculateAge(formData.dob) : "" }
    ];

    fields.forEach(field => {
      var label = document.createElement("label");
      label.textContent = field.label;
      fieldset.appendChild(label);

      var input;
      if (field.type === "select") {
        input = document.createElement("select");
        field.options.forEach(optionValue => {
          var option = document.createElement("option");
          option.value = optionValue;
          option.text = optionValue;
          if (optionValue === field.selected) option.selected = true;
          input.appendChild(option);
        });
      } else {
        input = document.createElement("input");
        input.type = field.type;
        input.value = field.value;
      }

      input.name = field.name;
      input.classList.add("form-control", "mb-3");
      fieldset.appendChild(input);
    });

    parent.appendChild(fieldset);
  }
}

// Example call to addAdultFields (ensure this is called after the DOM is loaded)
document.addEventListener('DOMContentLoaded', () => {
  // Call this function as needed, e.g., on some event or user action
  document.getElementById("numberofAdults").addEventListener('change', addAdultFields);
});


the second step of the multi step form is where the field should appear

<div id="adultFormcontainer" ></div>

when I run my code it does create the field and has the firstname ,lastname and Gender but calculating the age is the problem. when I remove the calculate age function I see the dob on the console

here is what my console looks like

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật