Forms and Keyboard Events
Learn how to work with forms and keyboard events.
We'll cover the following...
Forms
Forms are a very common method of interacting with a web page and can be found on many sites.
Traditionally, when a form is submitted, it’s sent to a server where the information is processed using a “back-end” language, such as Python or Ruby. However, it’s possible to stop the form being sent to the server and to instead use JavaScript on the “front end” to process the information.
Submitting a form
Let’s start with a simple form that contains one input field and a button for submitting the form. Let’s add the following code in the index.html
file:
<p>Enter your name in the box below:</p><form name='myForm'><input type='text' name='myName'><button type='submit'>Submit</button></form><div id='hello'></div>
This should produce an input box with a “Submit” button next to it. Note that the button has a type attribute of submit
: this will trigger a submit
event when it’s pressed. We’ve also added an empty <div>
element at the bottom of the code with an ID of hello
, which can’t be seen on the screen because it’s currently empty. We’ll be using this as a container to hold the output after the form has been submitted.
First of all, we need some references to these elements. Lets add the following code to the index.js
file:
const form = document.forms.myForm;
The DOM provides a convenient way of accessing any forms on a web page using document.forms
, which will return a ...