Practice Set, Week 10, Iterate over a form's fields

by jessupjs

HTML

<h3>Practice Set, Week 10, Iterate over a form's fields</h3>

<form id="myform">
    <fieldset>Contact Info
        <br>
        <br>Address
        <br>
        <input size="30" placeholder="Street Address" name="address" id="address" type="text" value="1 Story Street">
        <br>
        <br>
        <label for="city">City</label>
        <input size="20" placeholder="Town or City" name="city" id="city" type="text" value="Cambridge">
        <br>
        <label for="state">State</label>
        <input size="10" placeholder="State/Province" name="state" id="state" type="text" value="MA">
        <br>
        <label for="zip">Postal Code</label>
        <input placeholder="Postal Code" name="zip" id="zip " type="text" value="02138">
        <br>
        <br>Phone
        <br>
        <input size="16" placeholder="Phone Number" id="phone" name="phone" pattern="" type="text" value="(617)495-4024">
        <br>
        <br>
        <button type="submit" id="submitBtn" name="submit">Register Me!</button>
        <br>
    </fieldset>
</form>
<p></p>

CSS

\

JavaScript

/* Write your code here to iterate over the form's fields and output the values in each field to the console.  Your code should access the FORM object and iterate over the fields rather than get each form field by its ID.  

It should also work for a form of any number of fields, and work with any value typed into the field by a user. 
*/

// Added "click" event listener
var target = document.getElementById('submitBtn');
target.addEventListener("click", digestForm);

// Event listener function
function digestForm(e) {
  // suggested steps
  // 1)  get the form element from the page
  var f = document.forms["myform"];

  // 2) iterate over the form's elements array and write each element's value to the console
  var els = f[0].elements;

	console.log("Form submission results:")
  for (let i = 0; i < els.length - 1; i++) {
    console.log("  " + els[i].name + " : " + els[i].value)
  }
}