Reputation: 67
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.
Upvotes: 0
Views: 426
Reputation: 391
You have a few issues. One you need to have a way to get the data after the page loads.
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.
Upvotes: 2
Reputation: 89314
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);
Upvotes: 0
Reputation: 404
Use .unshift( object )
to prepend to an array.
let a = [1,2,3,4];
console.log( a );
a.unshift(5);
console.log( a );
Upvotes: 0