0

I know it's easy, but I can't quite get it.

function submitNewComment() {
   var noo = 0; //array index
   var userName = document.getElementById('user-name').value; //textbox
   var commentBox = document.getElementById('main-comment').value; //textbox
   var now = new Date();
   mili = now.getTime(); //time in milisecond
   var element = [];
   element.push({
      "no": noo, //array index
      "username": userName,
      "date": mili,
      "body": commentBox,
      "likes": "0",
      "parent": null
   });
console.log(element);
noo++;
console.log(noo);
}

In short, I need to add create a variable as an array containing objects. When I run the function, it doesn't quite work as I hoped. I am missing something.

The problem exists when you run the function for the second time. Ideally 2nd object should be created but the first one gets updated. So, at the end of 2nd run and every other run there after, length of the array remains 1.

  • What is `this.noo` outside the object? – brk Aug 06 '18 at 16:40
  • pls describe the question well. Where you get error? – Hossein Aug 06 '18 at 16:41
  • This is some weird code. What is `this` referring to here? Unless you call `submitNewComment` as a constructor, `this` will be the `window`. Also, what do you expect `element[this.noo]` to be? `this.noo` isn't defined anywhere so it will be `undefined`. – Angel Politis Aug 06 '18 at 16:44
  • duplicate of https://stackoverflow.com/questions/8073673/how-can-i-add-new-array-elements-at-the-beginning-of-an-array-in-javascript ?? – Steve Drake Aug 06 '18 at 17:40
  • Possible duplicate of [How can I add new array elements at the beginning of an array in JavaScript?](https://stackoverflow.com/questions/8073673/how-can-i-add-new-array-elements-at-the-beginning-of-an-array-in-javascript) – Steve Drake Aug 06 '18 at 17:40

3 Answers3

2

You have a few issues. One you need to have a way to get the data after the page loads.

  1. You need a button or some other method of action.
  2. You confusing yourself with your object creation. If it's a factory function for creating objects then 'this.[label]' is valid, but if you are just pushing form data as an object into an array then do as I've suggested below. Does what I did make sense?
  3. Also I didn't change it here, but the best way to create a date in milliseconds is Date.now(). Use this method going forward, it'll both shorten and simplify your code.
  4. Any questions?

var element = []; 
var btn = document.getElementById('btn');
btn.addEventListener('click', submitNewComment);
      
function submitNewComment() {
 var userName = document.getElementById('user-name').value
 var commentBox = document.getElementById('main-comment').value
 var now = new Date();
 var milliseconds = now.getTime();
  element.unshift({
    no: "test",
    username: userName,
    date: milliseconds,
    body: commentBox,
    likes: 0,
    parent: null,
  });
console.log(element);
}
 <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>misterhtmlcss</title>
  </head>
  <body>
  <input type="text" name="user-name" id="user-name">
    <input type="text" name="main-comment" id="main-comment">
    <button id="btn">Submit</button>
    <script src="index.js"></script>
  </body>
</html>

Update. I realized I left this declaration inside the function meaning it wouldn't retain continuous submissions which you may have wanted based on what you did say.

misterhtmlcss
  • 363
  • 1
  • 16
0

Use .unshift( object ) to prepend to an array.

let a = [1,2,3,4];
console.log( a );
a.unshift(5);
console.log( a );
Simranjit Singh
  • 384
  • 1
  • 6
0

You can use Array.prototype.unshift() to add elements to the start of an Array. This method returns the new length of the Array.

var element = [];
element.push({
      "no": "noo", //temp variable
      "username": "userName",
      "date": "mili",
      "body": "commentBox",
      "likes": "0",
      "parent": null
});
element.push({"something": "else"});
var newLen = element.unshift({"object": "one"});
console.log(element);
console.log("New length of Element Array: "+newLen);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • @brk @hossein@angel-politis @steve-drake @misterhtmlcss @simranjit-singh @hev1 The problem statement has been updated to provide more clarification. The problem was with the statement `var element = []` being declared in the function. – Yash Suryavanshi Aug 06 '18 at 18:36