1

I'm building dynamically with JavaScript a HTML page and setting an attribute with a text. Sometimes the text is a simple string and sometimes I have a JSON Object that I use JSON.stringify() to save it as a string.

 $("<a id=\"ftr\" myData=\"" + myString + "\" </a>").appendTo(myDiv);

And after that I extracting this attribute:

var temp = $(this).attr("myData"); // inside loop , $(this) refers to the correct link

When it's a simple text like this, everything works fine.

 <a id="ftr" myData="text test"></a>

But when extracting JSON object I get as a result only : "[{"

 <a id="ftr" myData="[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]></a>

How can I extract the full object in JSON format?

3 Answers 3

2

Use quotes properly

<a id="ftr" myData='[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]'></a>

Also I would suggest you to use data-* attributes like

<a id="ftr" data-mydata='[{"text":"test1","link":"http:\\www.google.com"},{"text":"test2","url":"http:www.google.com"}]'></a>

Then you can fetch using .data()

var temp = $(this).data("mydata");

DEMO

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

Comments

0

Quotations fixed

  <a id="ftr" myData="[{'text':'test1','link':'http:\\www.google.com'},{'text':'test2','url':'http:www.google.com'}]></a>

Comments

0

Well, one option is very simple: your code isn't working because you the double quotes in the JSON string close the HTML attribute value. So you could use single quotes in the HTML instead. (The other problem is that you never close the a tag.)

$('<a id=\'ftr\' myData=\'' + myString + '\'></a>').appendTo(myDiv);

DO NOT DO THIS

A far superior option is to stop serialising the data to JSON. You don't need to. jQuery has a fantastic data-storage functionality using the $.fn.data function, which can store complex data natively:

$("<a id=\"ftr\" />").data({data: dataObject}).appendTo(myDiv);

You can then access the data with the data function again:

$('#ftr').data('data')[0].link; // returns "http:\\www.google.com"

1 Comment

One other note: backslashes are used for escaping, so the string would actually be http:\www.google.com. And URLs use forward slashes anyway. This is irrelevant to your question, but may crop up as a problem for you down the line!

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.