Reputation: 29029
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
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
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
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