1

I have got about 100 PC Specification dropdowns like one of them is given below:

<select class="drpProcessor spec-gen" name="processor_id">
    <option value=""></option>
    <option value="23">Some Processor</option>               
</select>

What I want to achieve is an object of the whole specification (i.e. all the 100 spec dropdowns with their values in an object) like following:

var specs = {
    processor_id : 21,
    ram_id : 34,
    motherboard_id: 45,
    ...
    ...
};

I know that I can achieve this using something like the following:

var specs = {
    processor_id : $('.drpProcessor').val(),
    ram_id : $('.drpRam').val(),
    motherboard_id: $('.drpMotherBoard').val(),
    ...
    ...
};

But that would be a tedious job to do ( as I would have to write this for 100 dropdowns ). Fortunately, I have the name applied to each of the drop down that I would want to take as the respective spec's property. So I went on and wrote this little snippet that takes the name off of each of the drop down and tries to create this name a property of the specs object:

var els = $('#deassTab select');

// construct the specs object
var specs = {};
$(els).each(function( index, elem ){
   specs.($(elem).prop('name')) = $(elem).val(); // <-- Problem Lies here
})

But it doesn't allow me to do so and gives this error:

SyntaxError: Unexpected token (

The problem lies at specs.($(elem).prop('name')) i.e. where I am trying to add this property to the specs object via string. Is ther any way that I can achieve this i.e. create an object's property using string?

1
  • 3
    specs[elem.name] = elem.value; ??? Commented Mar 29, 2014 at 14:57

1 Answer 1

4

The error is the line:

specs.($(elem).prop(name)) = $(elem).val();

Where, when you want to use strings to dynamically set properties, you use square bracket syntax (and no dots) making that line:

specs[$(elem).prop(name)] = $(elem).val();

Which should resolve your problem.

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

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.