How To: Input Text on a JS Form
Follow these 6 steps to learn how to retrieve text input from a JavaScript form and display that text on the DOM.
Step 1: Retrieve the HTML values of the targeted elements, and assign JavaScript constants to each.
In the following example, we will assign a constant to the form element, the text input field, and the existing div
called “books-container”.
<!DOCTYPE html>
<html>
<head></head>
<body>
<form class="add-book-form">
<h3>What's Your Favorite Book?</h3>
<input type="text" id="new-title"
placeholder="Enter the book's title:"/>
<button type="submit">Submit</button>
</form>
<div id="books-container">
</div>
</body>
</html>
//JavaScript
const theForm = document.querySelector('.add-book-form');
const theBook = document.getElementById('new-title');
const theList = document.getElementById('books-container');
Step 2: Create an Event Listener to listen for the form submission. Use the .preventDefault()
method to keep the browser from refreshing after the user inputs their text.
//Use dot notation to attach the event listener to our constant:
theForm.addEventListener('submit', event => {
event.preventDefault();
})
Step 3: Retrieve the value of the text input field and assign it to a JavaScript constant. This line of code stays within the event listener block.
const inputBookTitle = theBook.value;
Step 4: Create a new element that will display the submitted text. Use .textContent
to display only the text part of the element.
const newBook = document.createElement('p');
newBook.textContent = inputBookTitle;
Step 5: Append the new input text element to the existing DOM element.
theList.appendChild(newBook);
Step 6: Clear the form using the reset()
method.
theForm.reset()
Putting all of the steps together, here is the complete JavaScript code for the HTML example provided at the beginning:
const theForm = document.querySelector('.add-book-form')
const theBook = document.getElementById('new-title')
const theList = document.getElementById('books-container')
theForm.addEventListener('submit', event => {
event.preventDefault()
const inputTitle = theBook.value
const newBook = document.createElement('p');
newBook.textContent = inputTitle;
theList.appendChild(newBook);
theForm.reset()
})
Read more on this topic:
MozDevNet. HTML: HyperText Markup Language | MDN, developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text. Accessed 1 Oct. 2023.