The submit
event is triggered when a form is submitted, either by clicking a Submit button, tabbing to the Submit button and pressing Enter/Return, or sometimes just by pressing Enter/ Return while a form element is in focus. Any way you can submit a form, this event gets triggered.
Adding a Listener to a Form submit Event
/* use the same adr method */ var adr = { /* ...previously defined methods go here... */ // define the method (aka the function) search: function(event) { /* prevent the default behavior */ event.preventDefault(); /* save the DOM element we're putting the output in */ var target = document.getElementById("output"); /* save the contacts JSON object to a variable */ var book = contacts.addressBook; /* save the length to a variable outside the loop for performance */ var count = book.length; /* ready the loop! */ var i; // clear the target area just in case there's something in it. target.innerHTML = ""; // check the count, of course and check to see if the value isn't empty if (count & gt; 0 & amp; & amp; searchValue !== "") { // loop through the contacts for (i = 0; i & lt; count; i = i + 1) { // look through the name value to see if it contains the searchterm string var obj = contacts.addressBook[i], isItFound = obj.name.indexOf(searchValue); // anything other than -1 means we found a match if (isItFound !== -1) { target.innerHTML += '<p>' + obj.name + ', <a href="mailto:' + obj.email + '">' + obj.email + '</a><p>'; } // end if } // end for loop } // end count check } // end method } // end adr object // save search field to a variable var searchForm = document.getElementById("search-form"); // activate autocomplete on submit searchField.addEventListener("submit", addr.search, false)
Something important to note from the search method in the form no longer submits per its default behavior when the search button is clicked. This is deliberate; if the form were to submit, you wouldn't be able to execute the JavaScript and update the page (it would have refreshed). You can stop a form submission by using the preventDefault() method.