function compactFormOutput(formElement) {
// Get all form elements
const formElements = formElement.elements;
// Iterate through each element
for (let i = 0; i < formElements.length; i++) {
const element = formElements[i];
// Check if the element is a text field or textarea
if (element.type === 'text' || element.type === 'textarea') {
// Output the label (if available)
if (element.label) {
console.log(`[${element.label}]`); // Label for context
}
// Output the element's name
console.log(` Name: ${element.name}`);
// Output the element's value
console.log(` Value: ${element.value}`);
} else if (element.type === 'select-one') {
// Output the label (if available)
if (element.label) {
console.log(`[${element.label}]`); // Label for context
}
// Output the selected option value
console.log(` Value: ${element.value}`);
} else if (element.type === 'checkbox') {
console.log(`[${element.name}] ${element.checked}`); //Name and checked state
} else if(element.type === 'radio'){
console.log(`[${element.name}] ${element.checked}`); //Name and checked state
}
}
}
// Example usage:
// Assuming you have a form with the id "myForm"
const myForm = document.getElementById('myForm');
if (myForm) {
compactFormOutput(myForm);
}
Add your comment