JS DOM: 33. HTML form

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>HTML Form Element</title>
  </head>
  <body>

    <form name="commentForm">
      <label for="comment">
        Comment : <input type="text" name="comment" id="comment" />
      </label>
      <br />
      <label for="from">
        From : <input type="text" name="from" id="from" />
      </label>
      <br />
      <input type="submit" value="Submit" />
    </form>

    <div id="commentList"></div>

    <script>
      document.querySelector("form[name=commentForm]").onsubmit = function (event) {
        event.preventDefault();

        const commentList = document.getElementById("commentList");
        const comment = document.getElementById("comment").value;
        const from = document.getElementById("from").value;

        const commentItem = document.createElement("p");
        commentItem.textContent = `${comment} - ${from}`;
        commentList.appendChild(commentItem);

        document.querySelector("form[name=commentForm]").reset();
      };
    </script>
  </body>
</html>