Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  148] [ 2]  / answers: 1 / hits: 35298  / 10 Years ago, mon, september 15, 2014, 12:00:00

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!


More From » jquery

 Answers
16

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';

[#69449] Friday, September 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;