Comment box lab
In this interactive lab, you'll be developing an interface where users can submit comments. These comments will be displayed in a list format right below the submission form without needing to refresh the page. By the end of this lab, you'll have a form that handles user inputs, validates them, and displays feedback.
Concepts
This lab involves the following concepts:
- DOM Manipulation: To interact with webpage elements, you need to understand how to select, create, and update elements using JavaScript.
- Event Handling: Understanding how to register and handle events on HTML elements like button clicks.
- Form Submission Handling: The lab requires interacting with form submission events and stopping them to prevent a page refresh.
Steps
-
Begin by creating an HTML form in your
index.html
file. This should include atextarea
and abutton
. Assign the ids 'comment' and 'submit' to them respectively. Use the attributeonsubmit="return false"
in your form element to prevent it from refreshing the page upon submission. -
Create a
p
(paragraph) element with the iderror
for displaying error messages. -
Create an unordered list (
ul
) with the idcommentList
. This is where your comments will be displayed in a list format. -
Move over to your
script.js
file. The goal here is to handle the form submission, show and manage the comments dynamically. Start by selecting your form inputs and error paragraph using thedocument.getElementById()
function in JavaScript and store them in respective variables. -
Add an event listener to your
submit
button for theclick
event. Inside the event listener function, perform an empty check on thecomment
textarea's value. If thecomment
textarea is empty, then display an error message inside theerror
paragraph. -
When the
comment
textarea has some text, clear the error message, create a new list item (li
), and append the comment as the text content of the list item. -
Append this new list item to the
commentList
unordered list. This shows the comment below the comment submission form. -
Finally, clear the
comment
textarea by setting its value to an empty string, signifying readiness to accept a new comment.
Please note you should refrain from giving solutions, and rather inspire a method of inquiry in these steps.
Hints
- To create a new HTML element using JavaScript, you can use the
document.createElement(element)
function, where 'element' is a string that specifies the type of element to be created. - Remember that JavaScript is case-sensitive. Be careful while writing the id's in your JavaScript file. They should match exactly with the HTML id's.