Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set JSON format to HTML5 data attributes in the jQuery

I'm trying these HTML

<div data-params="{a: 1, b: '2'}" id="TEST1"></div> <div data-params='{"a": 1, "b": "2"}' id="TEST2"></div> 

Then I use data() method in the jQuery

$('#TEST1').data('params'); //return a string $('#TEST2').data('params'); //return a object 

But TEST1 it's not a return object, but a string, it can only return object TEST2. But I want to get a object by TEST1, How do I do it?

=============

Finally, I choose to write a function to achieve their own needs

$.fn.data2 = function(key, value) {     if (value === undefined)      {         var data = $(this).data(key);         if (typeof(data) === 'string')          {             var _data = data.replace(/^[\s\r\n]*/g, '').replace(/[\s\r\n]*$/g, '');             if (_data.match(/\{.*\}/) || _data.match(/\[.*\]/)) {                 try {                     _data = (new Function( 'return ' + data ))();                     if (typeof(_data) == 'object') {                         $(this).data(key, _data);                         data = _data;                     }                 } catch(ex) {}             }         }         return data;     }     return $(this).data(key, value); }; 
like image 679
Jasper Avatar asked Sep 14 '11 01:09

Jasper


People also ask

How set value to data attribute in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})

How to get data from HTML form in JSON format?

We want to send the data of our HTML form directly to the JSON file. For this we are using json_encode() function which returns a JSON encoded string. We are making an array of values that the user fills in the HTML form. Then we pass this array into json_encode() function.


2 Answers

In order to be parsed as an object, the data attribute must be a well formed JSON object.

In your case you just need to quote the object keys (as you do in the second object). Try:

<div data-params='{"a": 1, "b": "2"}' id="TEST1"></div> 

For more info see the data method docs, the relevant part is this one (emphasis mine):

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string... ...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.

like image 164
Pablo Fernandez Avatar answered Sep 19 '22 04:09

Pablo Fernandez


You can escape the inner quotes:

<div data-params="{&quot;a&quot;: 1, &quot;b&quot;: &quot;2&quot;}" id="TEST2"></div> 

But there is nothing wrong with your second method:

<div data-params='{"a": 1, "b": "2"}' id="TEST2"></div> 

I would use that.

like image 43
Paul Avatar answered Sep 20 '22 04:09

Paul