1. function compactFormOutput(formElement) {
  2. // Get all form elements
  3. const formElements = formElement.elements;
  4. // Iterate through each element
  5. for (let i = 0; i < formElements.length; i++) {
  6. const element = formElements[i];
  7. // Check if the element is a text field or textarea
  8. if (element.type === 'text' || element.type === 'textarea') {
  9. // Output the label (if available)
  10. if (element.label) {
  11. console.log(`[${element.label}]`); // Label for context
  12. }
  13. // Output the element's name
  14. console.log(` Name: ${element.name}`);
  15. // Output the element's value
  16. console.log(` Value: ${element.value}`);
  17. } else if (element.type === 'select-one') {
  18. // Output the label (if available)
  19. if (element.label) {
  20. console.log(`[${element.label}]`); // Label for context
  21. }
  22. // Output the selected option value
  23. console.log(` Value: ${element.value}`);
  24. } else if (element.type === 'checkbox') {
  25. console.log(`[${element.name}] ${element.checked}`); //Name and checked state
  26. } else if(element.type === 'radio'){
  27. console.log(`[${element.name}] ${element.checked}`); //Name and checked state
  28. }
  29. }
  30. }
  31. // Example usage:
  32. // Assuming you have a form with the id "myForm"
  33. const myForm = document.getElementById('myForm');
  34. if (myForm) {
  35. compactFormOutput(myForm);
  36. }

Add your comment