Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Add Key Value Pair to an Empty Object

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

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 inputAttr should be an object and that I could add to that object. I must be mistaken. This was one of my many attempts to make this happen.

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

I also tried like this....

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

I thought maybe inputAttr should be an array instead, which seems to output a 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!

like image 371
VIDesignz Avatar asked Dec 01 '22 01:12

VIDesignz


2 Answers

Object properties are just accessed 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 via keys it is like a dictionary:

var inputAttr = {};
inputAttr["type"] = 'text';
inputAttr["value"] = 'New Value';
like image 185
Gone Coding Avatar answered Dec 04 '22 10:12

Gone Coding


Key-value for object can be set in this way:

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

Fiddle.

like image 30
Regent Avatar answered Dec 04 '22 09:12

Regent