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!
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';
Key-value for object
can be set in this way:
var inputAttr = {};
inputAttr.type = 'text';
inputAttr.value = 'New Value';
Fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With