3 step guide for building eventListener in a form button.
OK yall, Step one. Let’s get set up in our local envirnoment.
Create a folder to house your three files: index.html, script.css, and style.css.
Let’s test if our program is running correctly, open up the terminal and get up and running by typing: open index.html. This should open your program in the browser, in your browser you should see “Hello World”.
Delete the h1 tag with Hello world. Add an HTML <form></form> element with an action and method attribute set to “GET”. Add two input elements.
The first <input/> element will be where a user types in their name and it should have three attributes:
<input type="text" id="fname" placeholder="Name"/>
The second <input/> element will be our submit button and should have these three attributes:
<input type="button" id="btn" value="Submit"/>
Additionally, add a <p></p> tag at the top of the body section, later we will be able to display user’s input with <p> tag. Add an “display id on the p tag.
Open up your script.js file. Create a function titled function getName().
Let’s set up some DOM manipulation inside of our function:
Inside your function create a variable “n” and set it to:
let n = document.getElementById("fname").value;
Then target our display id, set its innerHTML value to n, which capturing whatever the input value entered by the user is.
document.getElementById("display").innerHTML = n;
Close out your function with a curly bracket, and create a document query to get the Id of “btn” and set an event Listeners to get triggered by a click event.
Our addEventListener will take two arguments: the first argument is the type of event occurring(i.e. “click”) and the second event is the function we want to have executed when the click event is triggered.
There you have it! Your browser should look something like this, where on Submit, the user’s input will be displayed in our <p> tag above the input:
While this form functionality is simple and to the point, it captures some of the most important and fundamental form event listening and dom manipulation. Click here for my code to use as a reference. Thanks for reading and happy hacking!