Adam
Adam

Reputation: 29029

Jquery: How to create a plain object with dynamic names?

I found in the docs that you can create an plain object like this:

var y = {
  name: "Pete",
  age: 15
};

However, I would like to add name and value dynamically to it, for example if we have something like:

<input type="text" name="$dynamicName" id="myinput">

That I can create an object like this:

var y = {
  name: "Pete",
  $('#myinput).attr('name'): $('#myinput).val(),
};

But this will throw an error:

SyntaxError: missing : after property id

How can I use $('#myinput).attr('name') as a name of a plain object?

Upvotes: 2

Views: 1920

Answers (3)

Rohit.007
Rohit.007

Reputation: 3502

Try using as an Array.

Like:

y[$('#myinput').attr('name')] = $('#myinput').val();

then you can access it as a simple object.

Upvotes: 3

Scath
Scath

Reputation: 3824

I think this is what you are wanting to do it will add the age item to the array and then set its value to whatever is in the textbox onclick.

var y = {
  name: "Pete"  
 };
function go(){
 y[$('#myinput').attr("name")] = $('#myinput').val();
console.log(y)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"name="age" id="myinput">
<input type="button"  onclick="go(); return false;">

Upvotes: 4

Will Jones
Will Jones

Reputation: 2191

Try using:

var y = {name: "Pete"};
y[$('#myinput').attr('name')] = $('#myinput').val()];

You also have unclosed single quotes:

var y = {
    name: "Pete",
    $('#myinput').attr('name'): $('#myinput').val(),
};

Upvotes: 0

Related Questions