It would be nice if the form were cleared
of its old data after it was submitted, so that the user could immediately start entering the
next order. Resetting the form is as simple as calling the <form>
element’s reset method.
Find the FormHandler.prototype.addSubmitHandler
method
in formhandler.js. At the end of the
this.$formElement.on('submit'...)
callback,
add a call to the form’s reset method:
... FormHandler.prototype.addSubmitHandler = function (fn) { console.log('Setting submit handler for form'); this.$formElement.on('submit', function (event) { event.preventDefault(); var data = {}; $(this).serializeArray().forEach(function (item) { data[item.name] = item.value; console.log(item.name + ' is ' + item.value); }); console.log(data); fn(data); this.reset(); }); }; ...
Save and enter some data into the form. When you submit the form, you should see that the data is cleared out.
Finally, add one last tweak to the UI.
When a form field is ready for input, it has
focus, as you saw in the last chapter. To set the focus on a specific form
field, you can call its focus method.
(The autofocus
attribute you added to the coffee order field
only takes effect when the page first loads.)
You can conveniently access the individual form fields via
the form’s elements
property. The elements
property is an array of the form’s fields, which you can refer to by their
indices, starting with 0.
In formhandler.js, right after the call to
this.reset in the submit
handler callback,
invoke the focus method on the first
field.
... FormHandler.prototype.addSubmitHandler = function (fn) { console.log('Setting submit handler for form'); this.$formElement.on('submit', function (event) { event.preventDefault(); var data = {}; $(this).serializeArray().forEach(function (item) { data[item.name] = item.value; console.log(item.name + ' is ' + item.value); }); console.log(data); fn(data); this.reset(); this.elements[0].focus(); }); }; ...
CoffeeRun is now jQuery-powered and can accept user input! You have bridged the gap between your HTML and your JavaScript modules. In the next chapter, you will complete the picture by creating interactive DOM elements based on the data captured from the form.
3.145.107.100