Week10.11 Form Handling - onsubmit

by Lucille Kenney

HTML

<h3>Form onsubmit event </h3>

<p>For any final checking you can't easily do while the form is being filled out, the form's "submit" event provides the means for checking everything before the submission happens.</p>

<form action="#" id="theForm" name="firstForm">
    <label for="age">Favorite Color: </label>
    <input type="text" name="color" size="8"/><br/>
    <label for="age">Favorite Food: </label>
    <input type="text" name="color" size="8"/><br/>
    <button type="submit" name="submit">Submit</button>
</form>

JavaScript

var f = document.forms[0];

/*  This handler will run when you submit the form    */
f.addEventListener("submit", function (e) {
    
    /// Here we can do whatever we want with the form
    //    and its elements. 
    for (var i=0; i< f.elements.length; i++){
         console.log(f.elements[i].value);   
    }
    
    // if things aren't right, I can cancel the form
    //  submission right here:
    e.preventDefault();    

});