Arrays of Objects

Example 1

In this example, we create a new "car" object and add its text representation to the textarea below

Code:

<script>
var cars = [];
var fields = ["make", "model", "year"];
function addCar(){
	var el;
	var newCar = new Object();
	for(x in fields){
		el = document.getElementById(fields[x]);
		newCar[fields[x]] = el.value;
	}
	cars.push(newCar);
	clearFields();
	updateTextBox();
	
}
function updateTextBox(){
	var el = document.getElementById("myList");
	el.innerHTML = "";
	for(var x=0; x<cars.length; x++){
		el.innerHTML += cars[x].make.toString() + " ";
		el.innerHTML += cars[x].model.toString() + " ";
		el.innerHTML += cars[x].year.toString() + "\n";
	}
	
}
function clearFields(){
	for(x in fields){
		el = document.getElementById(fields[x]);
		el.value = "";
	}
}
</script>