I am trying to create an object and have the name of each object be unique. The objects will have a name, a number and a second number that is null (this I intend to calculate later).
Is it possible to have an object named after a variable of 1
then at the end of the function increase the variable so that the next object is 2
?
I am being alerted the value of the id number and it comes out as NaN
In my fiddle, I have a button to append each object in the array to a list so I can inspect them. They come out as [ object Object ]
.
Should this be an object of objects instead of an array of objects if I later want to use the number
field in each object to perform calculations?
The format I have my sample object in is what I believe I want to stick with (unless there is a reason to do it better another way) because it follows the example on w3schools.
What am I doing wrong?
HTML:
<input type="text" placeholder="Name" id="name"> <input type="text" placeholder="Number" id="number">
<br>
<button id="makeObject">Make Object</button>
<button id="show">Show Me The Objects</button>
<ul id="list"></ul>
JavaScript:
/*Sample ideal object
1 = {
name: John Doe
number: 52
newNumber: null
}
*/
var arrayOfObjects = [];
var id = 1;
$(document).ready(function(){
$('#makeObject').on('click', function(){
var number = (parseInt($('#Number').val()));
var name = $('#Name').val();
arrayOfObjects.push(id = {
number: number,
name: name,
newNumber: null
});
id++;
alert("The id is now: " + id);
$('#Number').val("");
$('#Name').val("");
});
$('#show').on('click', function(){
$('#list').html("");
for (i = 0; i < arrayOfObjects.length; i++) {
$('#list').append("<li>" + arrayOfObjects[i] + "</li>");
};
});
});