JQuery Add key value pair to empty object

In jQuery, I can add multiple attributes to an element like this ...

var input = $('<input/>').attr({ type : 'text', value : 'New Value'});


My question is how can I achieve this using a variable like this ...

var input = $('<input/>').attr(inputAttr);


I was under the assumption that there inputAttr

should be an object and what I might add to this object. I must be wrong. This was one of my attempts to do it.

var inputAttr = {};
inputAttr.add({ type: 'text' });
inputAttr.add({ value : 'New Value' });


I've tried this too ...

var inputAttr = {};
inputAttr.add('type: text');
inputAttr.add('value : New Value');


I thought that maybe there inputAttr

should be an array instead, which seems to output the correct string, but not sure how to make it an object (which I think it should be).

var inputAttr = [];
inputAttr.push('type: text');
inputAttr.push('value : New Value');

// Then added object brackets like so
var input = $('<input/>').attr({inputAttr});


Any help would be appreciated! Thank you in advance!


source to share

2 answers

Object properties are available only by name. It is not an array.

var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';

var input = $('<input/>').attr(inputAttr);


If you want to access them indirectly using keys, it's like a dictionary:

var inputAttr = {};
inputAttr["type"] = 'text';
inputAttr["value"] = 'New Value';




The key value for object

can be set as follows:

var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';


Fiddle .



All Articles