I have global form data stored in a JavaScript object
Sounds like you just need to loop over the json and populate the 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);
}
}
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>
Please or to participate in this conversation.