Home > Back-end >  Display user inputs in an array
Display user inputs in an array

Time:11-05

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 > 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>

CodePudding user response:

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 >
      <div >
        <div >${handle}</div>
        <div >${email}</div>
        <div >${date}</div>
      </div>
      <div >${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 > 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" ></div>

CodePudding user response:

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 > 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>

  • Related