CodeBlanks Logo Icon CodeBlanks

Comment form skeleton

JavaScript course · Expert · Lesson 32/63

Build the comment form with addEventListener and DOM.

Form skeleton

The comment form has a textarea and a submit button. We'll listen for the form's submit event and prevent the default behavior.

addEventListener("submit", ...) runs when the form is submitted. event.preventDefault() stops the page from reloading.

Inside the handler we find the textarea with commentForm.querySelector("#commentText") and read its text with .value.

Reading the input value

Inside the form handler we select the textarea with querySelector. The .value property gives the text the user typed.

Example: const text = commentInput.value;

We'll then pass the text to renderComment, which we'll write in the next lessons.

Exercise Add the submit listener

Add a submit listener on commentForm. Inside the handler call event.preventDefault(), find the #commentText input, read its text with .value, and call renderComment(text).

Show example solution
commentForm.addEventListener("submit", (event) => {
  event.preventDefault();
  const commentInput = commentForm.querySelector("#commentText");
  const text = commentInput.value;
  renderComment(text);
});

Test yourself

  1. Add the event listener

    commentForm.addEventListener("____", (event) => { event.preventDefault(); });
    Show answer
    commentForm.addEventListener("submit", (event) => { event.preventDefault(); });
  2. What does preventDefault do?

    event.preventDefault();
    • Prevents the default behavior of the event
    • Reloads the page
    • Clears the form
    • Triggers the event
    Show answer

    Prevents the default behavior of the event — Correct! preventDefault stops the default behavior (page reload).

  3. Match the form methods

    addEventListener
    Add event listener
    preventDefault
    Prevent default behavior
    querySelector
    Select element
    value
    Get input text

All lessons in Expert