0

I am in a situation here, i think its a simple one but i can't sort it out. I Have a HTML element where i should pass a json Object

code

var x = "<li id='tag_1'></li>"
var obj = {"name":"krishna","id":"krish1"}

when I convert this to html i want to get Like this

<li id="tag_1" data-options={obj}></li>

I tried $(x).data("options",{obj}), tried to pass as a string when creating the html element,but did'nt work

Thanks

2
  • 2
    JSON is a string, not an object, and also .data will not create data-options for you. Take a look at the jQuery spec of what it actually does. Commented Jan 23, 2015 at 9:57
  • {obj} is invalid syntax. You can simply use $(x).data('options', obj). It will, however, not be saved on the HTML tag but rather just in jQuery's memory. Example: $('body').data('foo', { foo: 'bar' }); $('body').data('foo'); gives Object {foo: "bar"}. Commented Jan 23, 2015 at 9:57

2 Answers 2

3

$(x).data("options",{obj}) is a perfectly good way to do it, provided you fix the syntax error. Just pass obj directly, and jQuery will save it as an object. It will not, however, be added as an attribute.

$(x).data("options",obj)

If you look at the documentation for .data() it specifies that your value doesn't have to be a string:

value
Type: Anything
The new data value; this can be any Javascript type except undefined.

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

5 Comments

i did this fiddel but not woking,i tried to get the options to html but not working
"It will not, however, be added as an attribute." It's just saved in memory to be accessed by $(x).data('options'). Also, you're recreating the jQuery object when you append it. You need to save the same object.
@Krishna It works fine. Your problem was that when you do $('<tag>') you create a new element. You need to save the reference to this element and then use that (as you can see using my fiddle).
So what change should i do in that fiddle... or what change in code should i do, to access that obj
@Krishna Did you see my link? Your answer is already there? Instead of $(x).foo(); $(x).abc(); then use var xx = $(x); xx.foo(); xx.abc();
1

Try $(x).attr("data-options",JSON.stringify(obj))

If you don't want it printed in your HTML use $(x).data("options",obj)

1 Comment

fiddle.jshell.net/Lt51nmkm

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.