Home > Software engineering >  How can I add a date stamp to comments added
How can I add a date stamp to comments added

Time:10-10

I have a simple form for readers to add comments. The comments entered are listed on the website when added. I would like to register the date the comment was entered and list that underneath the comment itself, as shown on the website. Can someone assist me with the JS code for this? Thanks, Paul

const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');


// array to store the comments
var comments_arr = [];

if(!localStorage.commentData){localStorage.commentData = [];}
else{
  comments_arr = JSON.parse(localStorage.commentData);
}

// to generate html list based on comments array
const display_comments = () => {
  let list = '<ul>';
   comments_arr.forEach(comment => {
    list  = `<li>${comment}</li>`;
  })
  list  = '</ul>';
  comments.innerHTML = list;
}

submit.onclick = function(event){
    event.preventDefault();
    const content = field.value;
    if(content.length > 0){ // if there is content
      // add the comment to the array
      comments_arr.unshift(content);
      localStorage.commentData = JSON.stringify(comments_arr);
      // re-genrate the comment html list
      display_comments();
      // reset the textArea content 
      field.value = '';
    }
}
window.addEventListener('load', display_comments);
<link href="comment.css" rel="stylesheet">

<form>
    <textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
    <h4>Responses</h4>
       <div id="comment-box"></div>

<script src="comment.js"></script>

CodePudding user response:

if you only want date stamp then remove the var current_time from the display_comments() function.

const display_comments = () => {
    var date = new Date();
    var current_date = date.getFullYear() "-" (date.getMonth() 1) "-"  date.getDate();
    var current_time = date.getHours() ":" date.getMinutes() ":"  date.getSeconds();
    var date_time = current_date " " current_time;
    let list = '<ul>';
    comments_arr.forEach(comment => {
    list  = `<li>${comment}   created at :  ${date_time}</li>`;
    })
    list  = '</ul>';
    comments.innerHTML = list;
}
  • Related