0

I need to create a comments board for an assignment that takes user inputs and displays them below the input field in a comments section, This is where I have gotten to but I am not sure how to finish off the script so that the inputted data is displayed

function sendMessage() {

    let emailjs = email.value;
    email.value = ""

    let handlejs = handle.value;
    handle.value = ""

    let messagejs = message.value;
    message.value = ""

    let userobject = {
        emailjs,
        handlejs,
        messagejs
    };

    let array = [];
    array.push(userobject);
    comments.innerHTML = 'this is the bit I need help with';
}
<!doctype html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport"
         content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Comment section</title>
      <link rel="stylesheet" href="style.css">
      <script src="code.js"></script>
   </head>
   <body>
      <div class="alert"> Your message has been sent</div>
      <h1> Spartak Swinford FC - Comment Section</h1>
      <form id="contactform" action="#">
      <fieldset>
         <legend>Message</legend>
         <span>Email : </span><input type="text" id="email" placeholder="Email"><br>
         <span>Handle: </span><input type="text" id="handle" placeholder="Handle"><br>
         <span style="position: absolute;"></span>
         <textarea name="message" id="message" cols="50" rows="8">Enter your message...</textarea>
         <br>
         <button id="btn" type="button" onclick="sendMessage()">Post</button>
         <div id="clientSideContent"></div>
      </fieldset>
      </form>
      <h1>Comments</h1>
      <div id="comments"> </div>
   </body>
</html>

1
  • The simplest way would be to join the array into a string and then set the inner html to that. comments.innerHTML = array.join(","); Commented Nov 4, 2022 at 13:26

2 Answers 2

1

If you set up your form properly, you can take advantage of form validation, submission, and resetting.

<form id="contactform" onSubmit="postComment(event, this)" autocomplete="off">
  <!-- form items -->
  <button type="submit">Post</button>
</form>
const postComment = (e, form) => {
  e.preventDefault();
  const formData = new FormData(form);
  addComment({
    email: formData.get('email'),
    handle: formData.get('handle'),
    message: formData.get('message'),
    date: new Date().toISOString()
  });
  form.reset();
  renderComments();
  return false;
};

Full demo

I included logic for loading and saving comments to localStorage. It will not work in this sandbox, but it will work if you run this code on a web server.

const commentListElement = document.getElementById('comments');

const loadComments = () => {
  try {
    return JSON.parse(localStorage.get('comments')) ?? [];
  } catch (e) {
    console.log('Cannot load comments');
  }
  return [];
};
  
const saveComments = (comments) => {
  try {
    localStorage.set('comments', JSON.stringify(comments));
  } catch (e) {
    console.log('Cannot save comments');
  }
};

const comments = loadComments();

const addComment = (comment) => {
  comments.push(comment);
};

const createElementFromHTML = (htmlString) => {
  const node = document.createElement('div');
  node.innerHTML = htmlString.trim();
  return node.firstChild;
}

const commentToHtml = ({ date, email, handle, message }) =>
  createElementFromHTML(`
    <div class="flex-col comment">
      <div class="flex-row comment-info">
        <div class="comment-handle">${handle}</div>
        <div class="comment-email">${email}</div>
        <div class="comment-date">${date}</div>
      </div>
      <div class="comment-message">${message}</div>
    </div>
  `);

const renderComments = () => {
  commentListElement.innerHTML = '';
  comments.forEach(comment =>
    commentListElement.append(commentToHtml(comment)));
};

const postComment = (e, form) => {
  e.preventDefault();
  const formData = new FormData(form);
  addComment({
    email: formData.get('email'),
    handle: formData.get('handle'),
    message: formData.get('message'),
    date: new Date().toISOString()
  });
  form.reset();
  renderComments();
  return false;
};
.hidden { display: none; }
.flex-row { display: flex; }
.flex-col { display: flex; flex-direction: column; }

.comment { gap: 0.5rem; border: thin solid grey; padding: 0.25rem; }
.comment-info { gap: 0.5rem; border-bottom: thin solid grey; }
.comment-handle { font-weight: bold; }
.comment-email { color: #444; }
.comment-email::before { content: '<'; }
.comment-email::after { content: '>'; }

#comments { gap: 1rem; }
<div class="alert hidden"> Your message has been sent</div>
<h1> Spartak Swinford FC - Comment Section</h1>
<form id="contactform" onSubmit="postComment(event, this)" autocomplete="off">
  <fieldset>
    <legend>Message</legend>
    <div>
      <label>Email : </label>
      <input type="text" name="email" placeholder="Email" pattern="\w+@\w+\.\w+" required>
    </div>
    <div>
      <label>Handle:</label>
      <input type="text" name="handle" placeholder="Handle" required>
    </div>
    <textarea name="message" name="message" cols="50" rows="8" placeholder="Enter your message..." required></textarea>
    <br>
    <button type="submit">Post</button>
  </fieldset>
</form>
<h1>Comments</h1>
<div id="comments" class="flex-col"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

This is how you can do it, you can add li and all on your own.

let email = document.getElementById("email");
let handle = document.getElementById("handle");
let message = document.getElementById("message");
let comment = document.getElementById("comments");
let button = document.getElementById("btn");

button.addEventListener("click", sendMessage);

function sendMessage() {
  let emailjs = email.value;
  email.value = ""

  let handlejs = handle.value;
  handle.value = ""

  let messagejs = message.value;
  message.value = ""

  let demo = emailjs+ " " + handlejs + " " + messagejs;
  comment.innerHTML += demo;
}
<div class="alert"> Your message has been sent</div>
<h1> Spartak Swinford FC - Comment Section</h1>
<form id="contactform" action="#">
  <fieldset>
    <legend>Message</legend>
    <span>Email : </span><input type="text" id="email" placeholder="Email"><br>
    <span>Handle: </span><input type="text" id="handle" placeholder="Handle "><br>
    <span style="position: absolute;"></span>
    <textarea name="message" id="message" cols="50" rows="8" placeholder="Enter your message..."></textarea>
    <br>
    <button id="btn" type="button">Post</button>
    <div id="clientSideContent"></div>
  </fieldset>
</form>
<h1>Comments</h1>
<div id="comments"> </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.