1

How can I use an HTML attribute value as a JQuery object with $.param?

<div data-sd="{a:1,b:1,c:2}"></div>

When I try this I got strange results.

<script type="text/javascript">
var v = $.param($('div').data('sd'));
</script>
2
  • Can you explain 'strange results' and what you are expecting? Commented Sep 15, 2012 at 13:54
  • @dSquared: Since data-sd is not a well-formed JSON object, $.param will actually try to convert the string "{a:1,b:1,c:2}", yielding 0=%7B&1=a&2=%3A&3=1&4=%2C&5=b&6=%3A&7=1&8=%2C&9=c&10=%3A&11=2&12=%7D instead of a=1&b=1&c=2. Commented Sep 15, 2012 at 14:11

1 Answer 1

4

Wrap your object's property names with double-quotes, in order to have well-formed JSON:

<div data-sd='{"a":1,"b":1,"c":2}'></div>​​​​​​​​​​​​​​​​​​​

Then, $.param will return a=1&b=1&c=2, as expected. DEMO.

From HTML5 data-* Attributes:

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

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

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.