1

How can I set a property of my object to a variable? The variable is equal to a form textfield value. Both obj.property and obj[property] give me a undefined error when I display the mycar object.

function auto(manufacturer,model,engine_size,year,color,price) 
{
    this.manufacturer = manufacturer;
    this.model = model;
    this.engine_size = engine_size;
    this.year = year;
    this.color = color;
    this.price = price;
}

var mycar = new auto();

var a = document.form.num1.value;
mycar.manufacturer = a;
mycar[manufacturer] = a;

sorry. here is all of my code http://jsfiddle.net/vzqjv/

im trying to set my object property to a variable, a, which is equal to a form textfield value after some validation to see if it checks out.

11
  • Is this the entire code? Commented Apr 30, 2013 at 3:23
  • are you sure that "a" is not undefined? Commented Apr 30, 2013 at 3:24
  • @KhanhTo: But that won't give an error (on the mycar lines), will it? Commented Apr 30, 2013 at 3:26
  • because if "a" is undefined, when he assigned an undefined value to mycar.manufacturer, the mycar.manufacturer will be undefined. Commented Apr 30, 2013 at 3:28
  • @KhanhTo - And that is completely legal. That will not cause an undefined error, just an undefined assignment. Commented Apr 30, 2013 at 3:29

4 Answers 4

1

mycar.manufacturer = a assigns a to a property of mycar named manufacturer.

mycar[manufacturer] = a assigns a to a property of mycar with the same name as the value of a variable manufacturer. You probably meant mycar["manufacturer"] = a.

Sign up to request clarification or add additional context in comments.

Comments

1

You haven't declared your variable manufacturer, so it is undefined when you do mycar[manufacturer] = a;. You need to either define it

var a = document.form.num1.value,
    manufacturer = "manufacturer";
mycar.manufacturer = a;
mycar[manufacturer] = a;

or use quotes:

var a = document.form.num1.value;
mycar.manufacturer = a;
mycar["manufacturer"] = a;

Comments

1

The second notation

mycar[manufacturer] = a;

should be

mycar["manufacturer"] = a;

The first notation should work. Are you modifying mycar in a way that we don't see?

My guess is that the undefined error is actually on this line:

var a = document.form.num1.value;

is that being defined correctly?

1 Comment

document.form.num1.value; seems to be returning correctly according to dev tools. It's probably just the mycar[manufacturer]!
0

You didn't give the definition of the auto. I guess you don't have the manufacturer property in it. Another way is just do

var mycar = {};
var a = document.form.num1.value;
mycar.manufacturer = a;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.