mpen mpen -3 years ago 115
jQuery Question

Does jQuery automatically decode data-* attributes?

I was trying to do this,

var worker_ids = $.parseJSON($(':selected',this).data('workers'));

But I kept getting back
. So I tried just logging


And it gave me back my workers as an array!

My HTML looks something like:

<option value="77" data-workers="[&quot;2287&quot;,&quot;2137&quot;]">COOL KIDS</option>

I would have expected it to come back as a string which I would have to parse.

This happens to work perfectly fine for me, but it doesn't seem like a very good design decision. What if my attribute just happened to look like JSON?

Answer Source

Yes, jQuery does attempt to guess at the data type that is stored on the data attribute and converts it when using .data (also applies for numbers, objects, and so on).

To get the raw attribute value, use .attr('data-workers')

The actual operation is performed by the internal dataAttr function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download