Danny971's avatar

How to Integrate Global Variable Data into Dynamically Generated Form Fields

Hello everyone,

I'm working on a form in my Laravel application where users can specify the number of adults, and based on that number, input fields are dynamically generated. Additionally, I have some global form data that should be pre-filled in the first set of input fields.

Current Scenario:

Users enter the number of adults in an input field. Based on this number, a corresponding number of input fields are generated. I have global form data stored in a JavaScript object, which should populate the first set of input fields (adult section)

here is my code

// Debounce function to limit the rate at which a function is executed
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}

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

};

// 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"]');
  

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

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

// Debounced saveFormData function
const debouncedSaveFormData = debounce(saveFormData, 3000);

// 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"]');
 

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


function addAdultFields() {
  // Get the number of adults specified in the input element
  var numAdults = document.getElementById("numberofAdults").value;

  // Get the parent element to which we'll add the new form fields
  var parent = document.getElementById("adultFormcontainer");

  // Remove any existing form fields (in case the number of adults was changed)
  while (parent.lastChild) {
    parent.removeChild(parent.lastChild);
  }
 /////////global variable test//////////////////////////
 
  // Create and add the global form data section
  var globalFormFieldset = document.createElement("fieldset");
  globalFormFieldset.style.display = "flex";
  globalFormFieldset.style.flexDirection = "row";
  globalFormFieldset.style.marginBottom = '100px'; // add margin to the bottom
  globalFormFieldset.style.paddingTop = '5px'; // add padding to the bottom

  var globalLegend = document.createElement("legend");
  globalLegend.textContent = "Global Form Data";
  globalFormFieldset.appendChild(globalLegend);

  // Define the fields for global form data
  var fields = [
    { label: "First Name", id: "globalFirstName", name: "firstName", type: "text", placeholder: "First Name", value: formData.firstName },
    { label: "Last Name", id: "globalLastName", name: "lastName", type: "text", placeholder: "Last Name", value: formData.lastName },
    { label: "Gender", id: "globalGender", name: "gender", type: "select", options: ["Male", "Female"], selected: formData.gender },
    
  ];

  fields.forEach(field => {
    var label = document.createElement("label");
    label.setAttribute("for", field.id);
    label.textContent = field.label;

    var input;
    if (field.type === "select") {
      input = document.createElement("select");
      input.setAttribute("id", field.id);
      input.setAttribute("name", field.name);
      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.setAttribute("type", field.type);
      input.setAttribute("id", field.id);
      input.setAttribute("name", field.name);
      input.setAttribute("placeholder", field.placeholder);
      input.classList.add("form-control");
      input.value = field.value;
    }

    input.classList.add("mb-3");
    globalFormFieldset.appendChild(label);
    globalFormFieldset.appendChild(input);
  });

  // Add the global form data section to the parent
  parent.appendChild(globalFormFieldset);

 /////////end of global variable test/////////
  // testing this object will hold the value of the input field
  var adultfirstnameformdata = {};

  // Generate a new set of form fields for each adult
  for (var i = 1; i <= numAdults; i++) {

    // create a fieldset to hold the adult info
    var fieldset = document.createElement("fieldset");

    //styling the field set 

    //fieldset.style.border = "1px outset gray";

    fieldset.style.display = "flex";
    fieldset.style.flexDirection = "row";

    fieldset.style.marginBottom = '100px'; // add margin to the bottom
    fieldset.style.paddingTop = '5px'; // add padding to the bottom

    /*fieldset.style.backgroundColor ="blue";*/

    // we want the adult information to be on the left of the container while the child info is on the right 
    fieldset.classList.add("float-left");

    // a legend should be create for the adult info
    var legend = document.createElement("legend");
    legend.textContent = "Adult" + i;


    // Create a new label element for the adult's name
    var nameLabel = document.createElement("label");
    nameLabel.classList.add("inline-block");
    //nameLabel.setAttribute("for", "adult" + i + "First Name");
    nameLabel.textContent = "First Name";  // "Adult " + i + " First Name:"

    // Create a new input element for the adult's name
    var nameInput = document.createElement("input");
    nameInput.setAttribute("type", "text");
    nameInput.setAttribute("id", "adult" + i + "FirstName");
    nameInput.setAttribute("name", "adult" + i + "FirstName");
    nameInput.classList.add("form-control");
    nameInput.classList.add("mb-3");





    // last name 

    // Create a new label element for the adult's last name
    var lastNameLabel = document.createElement("label");
    lastNameLabel.classList.add("inline-block");
    lastNameLabel.setAttribute("for", "adult" + i + "LastName");
    lastNameLabel.textContent = "Last Name:";


    // Create a new input element for the adult's last name
    var lastNameInput = document.createElement("input");
    lastNameInput.setAttribute("type", "text");
    lastNameInput.setAttribute("id", "adult" + i + "LastName");
    lastNameInput.setAttribute("name", "adult" + i + "LastName");
    lastNameInput.classList.add("form-control");
    lastNameInput.classList.add("mb-3");



    ///

    // Create a new label element for the adult's age
    var ageLabel = document.createElement("label");
    ageLabel.setAttribute("for", "adult" + i + "Age");
    ageLabel.textContent = "Age:";


    // Create a new input element for the adult's age
    var ageInput = document.createElement("input");
    ageInput.setAttribute("type", "text");
    ageInput.setAttribute("id", "adult" + i + "Age");
    ageInput.setAttribute("name", "adult" + i + "Age");

    ageInput.classList.add("form-control");
    ageInput.classList.add("mb-3");


    // Create a new label element for the adult's gender
    var genderLabel = document.createElement("label");
    genderLabel.setAttribute("for", "adult" + i + "gender");
    
    genderLabel.textContent = "Gender:";

    // Create a new select element for the adult's gender
    var genderInput = document.createElement("select");
    genderInput.setAttribute("id", "adult"  + i + "gender");
    genderInput.setAttribute("name", "adult" + i +"gender");
    genderInput.classList.add("form-control");

    // Create options for the select element
    var maleOption = document.createElement("option");
    maleOption.value = "Male";
    maleOption.text = "Male";
    genderInput.appendChild(maleOption);

    var femaleOption = document.createElement("option");
    femaleOption.value = "Female";
    femaleOption.text = "Female";
    genderInput.appendChild(femaleOption);

    /*
   // Create a new input element for the adult's gender
   var genderInput = document.createElement("input");
   genderInput.setAttribute("type", "text");
   genderInput.setAttribute("id", "adult");
   genderInput.classList.add("form-control");
   
   */

    // Add the new form fields to the fieldset element
    //the created elements should be appended to the fieldset and not the parent


    parent.appendChild(fieldset); //only fieldset should be appended to parent
    fieldset.appendChild(legend);

    fieldset.appendChild(nameLabel); //
    fieldset.appendChild(nameInput);
    fieldset.appendChild(lastNameLabel);
    fieldset.appendChild(lastNameInput);
    fieldset.appendChild(ageLabel);
    fieldset.appendChild(ageInput);
    fieldset.appendChild(genderLabel);
    fieldset.appendChild(genderInput);

  }


}
0 likes
25 replies
jlrdw's avatar

I have global form data stored in a JavaScript object

Sounds like you just need to loop over the json and populate the fields.

1 like
jlrdw's avatar

@Danny971 First make sure to watch some refactoring videos from @jeffreyway

Just Examples

When I develop at times I throw all in main function to make sure all works:

response.json().then(function (data) {
        var div = document.getElementById('msg');
        document.getElementById("msg").style.display = "block";
        for (var key in data) {
            div.innerHTML += " " + data[key];
        }

Which is sloppy. But after getting all done I refactor, usually goes fairly quick.

Now see this:

try {
        const response = await axios.put(url, $post);
        var data = response.data;
        showData(data);
    } catch (error) {
        if (error.response) {
            showData(error.response.data);
        }
    }

The first call to showData is to display the success message or whatever. But note that I can use the same function to show errors as well.

The showData function is just:

function showData(data) {
        var div = document.getElementById('msg');
        document.getElementById("msg").style.display = "block";
        for (var key in data) {
            div.innerHTML += " " + data[key];
        }
    }

This way I can show validation errors in a div. Like The email field is required instead of just 422.

Your main function keep short and learn to call some functions to handle some of the stuff.

1 like
Danny971's avatar

@jlrdw thanks for the guideline. the link you shared was an eye opener. Im still trying to figure out where I need to put the global variable to loop through the get the field created and populated witht global variable data

1 like
martinbean's avatar

@danny971 To be honest, you look like you’d be better off using something that uses reactivity like Alpine or Vue. It would massively reduce the number of lines of JavaScript, and be less error-prone.

1 like
Danny971's avatar

I solved it . thanks guys for your advise on refactoring

Danny971's avatar

@jlrdw @jeffreyway @martinbean

i did simplify my code. I hope I did it the right way as you were saying but now i'm trying to generate the age based on the date of birth

here is the code

// 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
  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);
  }
}

with my calculateAge function I dont see the dateofbirth on the console.log

but I when I remove it I see it what am I doing wrong

Danny971's avatar

@martinbean cause the fields varies

so if we enter two adult it will generate for two adults based on the number entered

here

     <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>
jlrdw's avatar

@Danny971 If they want to add another just use a popup modal.

Also just make a simple form and post with Axios JS.

You should be able to cut all that down to a few lines of code.

Edit:

Here is example using formData with an image also:

    const buttonForm = document.getElementById("submit");
    buttonForm.addEventListener("click", async (event) => {
        event.preventDefault();
        const thisForm = document.getElementById('signup');
        var formData = new FormData(thisForm);
        var url = '<?php echo DIR . "dog/addjs"; ?>';   // custom to my app
        axios({
            method: "post",
            url: url,
            data: formData,
       })
                .then(function (response) {
                    if (response.status == 200) {
                        alert(response.status);
                    }
                    console.log(response);  // real app show in a div
                })
                .catch(function (response) {
                    console.log(response);   // real app show in a div
                });
});

Just short example while I was learning axios js.

But there are several techniques to using axios js. See examples.

Use the axios js technique you prefer.

Note, It works with formData on a post, I had trouble with put. Had to use JS to get the inputs.

Danny971's avatar

@jlrdw no I should use this cause its the only way to roll smoothly with the other requirement and to keep the UI flowing

jlrdw's avatar

@Danny971

its the only way to roll smoothly with the other requirement and to keep the UI flowing

That's what ajax is for, you show a success message and user moves on to where they need to go next.

A simple next step button would work.

I suggest taking more javascript and ajax lessons. It generally doesn't take that many lines of code.

Danny971's avatar

@jlrdw it a multi step form

the first step is where you set the amout of adults

the second step Is the area where you see the first name last name gender and age

and where you manually insert the rest

jlrdw's avatar

@Danny971 exactly that's what a couple of modals could be used for.

After all is filled as needed data is sent via ajax.

You hide the modal until needed. (modal or just hidden divs) however you need to do it.

You could refactor all to much simpler.

You said earlier:

cause the fields varies

How possible? You still need matching DB fields in the database. So don't have fields that vary, instead show fields when needed.

Many times I write out and draw with pencil and paper what's needed, it helps visualize the project better.

Edit:

For related data (foreign data) yes this part do as needed, but put some of the work in a function you can call, so you don't have one huge function.

I showed earlier how to use other functions for some of the work.

But exactly what isn't working?

martinbean's avatar

@Danny971 Yeah, but there are far better ways to do this. Like I mentioned the other day, you’re better off using a library that has reactivity (i.e. Alpine or Vue) instead of all this horrible DOM manipulation and manually creating and appending elements in JavaScript.

If you want to dynamically create a number of inputs based on the value of another, then this would be pretty easy with something like Alpine. I’ve created a JSFiddle example here: https://jsfiddle.net/martinbean/xf9ew5Lg/17/

16 lines of HTML with a few Alpine directives to automatically generate fields (as well as disable the submit button until adult details are provided). Your HTML is also separated from the behaviour, meaning you can change your mark-up to suit your website design much easier without having to rewrite loads of JavaScript.

Danny971's avatar

@martinbean oh I thought writing pure Javascript code was the best thing to do. the example you gave does look simple but I did solve the issue I might still implement it later with Alpine. I change this

     
                                                <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>

to

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

the change was from type text to type date

but do you know any other ways to get data from one step of a multi step from to the other

I used global variables but am not sure for certain if its the global variables are causing this issue.

the issue is that sometimes it takes the date of birth and calculate it and display the age the text field.

it works now and next few seconds trying again it wont work

i constantly have to keep clearing the cache in the browser to get it to work

what do you think might be the issue ?

jlrdw's avatar

@Danny971 you can pass data to another page via a json array. If session data, use a json array to pass it.

But I thought you were wanting to add users on the fly. Which should be easy either using @martinbean suggestion or javascript.

What did you mean by Global Variable Data?

Edit:

I often have apps where I add on the fly, I put the table in an object like:

Alt image

Alt image

Clicking add new brings up an add form. Note, just examples and images were taken from a work in progress app.

A good series is https://laracasts.com/series/javascript-techniques-for-server-side-developers

https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies

Also you do realize there are many free javascript lessons right here on laracasts.

@martinbean solution seems easier once you learn how.

Danny971's avatar

@jlrdw thanks for your information and the links you provided by global variables I means this

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

I have a multi step form

here is what it looks like

 <div class="card-body">
                                <form action="{{url('requestFormData')}}" id="step-form-horizontal" class="step-form-horizontal" method="POST" >
                                    
                               

                                    <div>
                                        <h4>Client Info</h4>
                                        @csrf
                                        <section >
                                           
                                            
                                            <div class="row">

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


                                                              <div class="col-lg-2 mb-4">
                                                    <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>

                                                <div class="col-lg-2 mb-4">
                                                    <div class="form-group">
                                                        <label class="text-label">Number of Children*</label>
                                                        <input type="number" name="numberofChildren" id = "numberofChildren" min ="0"  class="form-control" onchange="addChildrenFields()" required >
                                                    </div>
                                                </div>
                                                
                                              </div> <!-- end of address row  -->

                                            

                                    
                                                <div class="row">

                                     

                                                </div>
                                            
                                    
                                               
                                        </section>
                



                                        <h4>Family Deographics</h4>
                                        
                                        <section >
                                           
                                        
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Family Deographics </h4>
                            </div>
                            <div class="card-body">
   
                                                
                                                
                                         <div class = "familycontainer family-demo-scrollbar">

                                         <div id="adultFormcontainer" ></div>
                                        <div id="children-form-container" ></div>

                                        </div>

                            </div>
                        </div>
                                        </section>

in the code above client Info section is the first step of the multi step form and family demographics is the second step

so I created global variable to store the data of first name , last name , dob, gender

so it can be used to create and populate the field of the head of house hold in family deographics.

yes you are right @martinbean gave alot of valuable resources and I will employ them.

well I wouldn't say I am an expert in JS because I was more focusing on backend developement and I also use MDN alot for JS

jlrdw's avatar

@Danny971 You can do one at a time, and just have an Add More button. Which my example does it like that, it adds a checking account entry.

Added via ajax, form set back to display none, and table is loaded.

But again just an alternative suggestion.

And formData is to submit your whole form.

So if you go that route, have a loop that makes that many inputs like @martinbean showed. Yes Alpine is probably easier, but it can easily be done in blade with or without javascript.

You don't need to use javascript for everything.

Danny971's avatar

@jlrdw I will do it over with Apline and formData is not to submit the whole form . like I said it global variables for me to catch what the user input on client Info so we can have that data as adult 1 or head of house hold on family demographics

I will post a pic of how it work to get you and Idea

Danny971's avatar

@jlrdw if I were to use Apline.js would I be able to write code to calculate the age from date of birth ?

martinbean's avatar
Level 80

if I were to use Apline.js would I be able to write code to calculate the age from date of birth ?

@Danny971 Yes. Just calculate the age from the specified birth date:

<form x-data="{
  form: {
    birth_date: null,
  },
  get age() {
    if (this.form.birth_date) {
      // TODO: Logic to calculate age here
    }

    return null;
  },
}">
  <label for="birth_date">Birth date</label>
  <input
    id="birth_date"
    name="birth_date"
    type="date"
    x-model="form.birth_date"
  >
  <template x-if="age > 0">
    <p>You are <span x-text="age"></span> years old.</p>
  </template>
</form>
Danny971's avatar

@martinbean wow that is really simple and quick. I will diff implement this later down cause I have a deadline to meet this week for this sprint and since I already got it to work the other way I will submit that and later come back to redo it in Apline. you learn something new everyday. Never heard of Alpine before this discussion.

I have another issue in trying to submit my captured data to the database I don't get the ages for the adults in the controller

the Javascript is the same as I posted before (using this temporary before the deadline)

here is the controller

    
        // the adult first name
      // Initialize arrays to store extracted data
$adult_first_names = [];
$adult_last_names = [];
$adult_age = [];
$adult_gender = [];

// Extract first names
foreach ($_POST as $key => $value) {
    if (strpos($key, "adult") === 0 && strpos($key, "FirstName") !== false) {
        $adult_number = intval(str_replace("adult", "", str_replace("FirstName", "", $key)));
        $adult_first_names[$adult_number] = $value;
    }
}

// Extract last names
foreach ($_POST as $key => $value) {
    if (strpos($key, "adult") === 0 && strpos($key, "LastName") !== false) {
        $adult_number = intval(str_replace("adult", "", str_replace("LastName", "", $key)));
        $adult_last_names[$adult_number] = $value;
    }
}


// Extract ages
foreach ($_POST as $key => $value) {
    if (strpos($key, "adult") === 0 && strpos($key, "Age") !== false) {
        $adult_number = intval(str_replace("adult", "", str_replace("Age", "", $key)));
        $adult_age[$adult_number] = $value;
    }
}

dd($adult_age);

// Extract genders
foreach ($_POST as $key => $value) {
    if (strpos($key, "adult") === 0 && strpos($key, "Gender") !== false) {
        $adult_number = intval(str_replace("adult", "", str_replace("Gender", "", $key)));
        $adult_gender[$adult_number] = $value;
    }
}
         


foreach ($adult_first_names as $key => $first_name) {
    DB::table('family_demographics')->insert([
        'firstname' => $first_name,
        'lastname' => $adult_last_names[$key] ?? '', // Handle missing last name
        'age' => $adult_age[$key] ?? null, // Handle missing age
        'gender' => $adult_gender[$key] ?? '', // Handle missing gender
        'family_id' => $familyId // Ensure $familyId is defined and valid
    ]);
}

i get and empty array for adult age and it doesnt capture the head of house hold section in the controller

Please or to participate in this conversation.