jQuery Add Key Value Pair to an Empty Object

31,377

Solution 1

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

Solution 2

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

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

Fiddle.

Share:
31,377
VIDesignz
Author by

VIDesignz

The ability to be freely expressive within the strict rules of scripting is very rewarding.

Updated on September 16, 2020

Comments

  • VIDesignz
    VIDesignz over 3 years

    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!