0

I am looking form a nested data to a DOM element. Something like this

$("div").data( "test", { 
    first: 16,
    last: "pizza!"
});

Here is my effort to make similar kind of format. But RefAttrValue variable is not behaving as variable.

for (var i = 0; i < reference.attributes.length; i++) {
    var RefAttrValue = (reference.attributes.item(i).name);
    $(tableCaption).data("referenceData").RefAttrValue = reference.attributes.item(i).value;
}

Here the Values of the "reference" is a XML. Which has value like below or can contain any similar XML.

<facilityreference Name="qtitem_fac" AttrTable='table1' colVal='table1colValue'></facilityreference>

I want to set up the data() format in this below format "Dynamically".

$("div").data("test",{ Name: "qtitem_fac", last: "table1colValue" });

Please help.

3 Answers 3

2

As far as I understand, you need something like this:

var datObj = {};
for (var i = 0; i < reference.attributes.length; i++) {
    var RefAttrValue = (reference.attributes.item(i).name);
    datObj[RefAttrValue] = reference.attributes.item(i).value;
}
$(tableCaption).data("referenceData", datObj );

In your code I see few problems: First: If you do nothing like $(tableCaption).data("referenceData", {...}) before you run your code, line $(tableCaption).data("referenceData") will return undefined and that will cause an exception.

If you have a field name in a variable (RefAttrValue in your case) you need to do something like $(tableCaption).data("referenceData")[RefAttrValue]. Such notation is a synonym, if RefAttrValue = "Name", to $(tableCaption).data("referenceData").Name

Doing this $(tableCaption).data("referenceData").RefAttrValue you simply access property of referenceData with name RefAttrValue.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I access the above stored data ? Will it be something like this ? $(tableCaption).data("referenceData").datObjValue; ?
Using your example, it will be $(tableCaption).data("referenceData").Name
1

Not tested:

 obj = {};

    $('facilityreference').each(function(){
       $.each(this.attributes, function(i, attrib){
           obj[attrib.name] = attrib.value;
      });

    }); // then do something with you object

Comments

-1
use this...Hopefully this will solve the requirement.!
str = $('#id').data('test');var json = JSON.stringify(eval("(" + str + ")"));alert(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.