Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Add new Objects from front end.......Javascript

My question is for example i have a constructor function

function Car(make, model, year) { this.make = make; this.model = model; this.year = year; }

var ford = new Car('Ford','Mustang GT', 2014 );

this created a new car named ford which will have properties of the Car constructor. I can add as many as i want on the js file, but what if I want to add more from the front end?

<input id='make/><input id='model'><input id='year'>

<button>Add new Car</button>

JS.... .... ......??

Any ideas?

function Car(make, model, year) { 
  this.make = make; 
  this.model = model; 
  this.year = year; 
}

var ford = new Car('Ford','Mustang GT', 2014 );

2 Answers

Steven Parker
Steven Parker
231,072 Points

:point_right: You can define a click handler for the button to make a new car object like this:

var button = document.getElementsByTagName("button")[0];
button.onclick = function() {
  var make = document.getElementById("make");
  var model = document.getElementById("model");
  var year = document.getElementById("year");
  var newcar = new Car(make.value, model.value, parseInt(year.value));
  // do something here with "newcar"
}

You still need to decide what to do with the new car object.

Steven, where were you when I was stuck on my Sass quiz last night and all day today....

Steven Parker
Steven Parker
231,072 Points

I do have a life away from the computer also!   :stuck_out_tongue_winking_eye:

Whoa...is there such a thing?

Thanks soo much loving the Treehouse Community!!!!!!