2

I constructed table row with custom data attributes, using php:

<tr id="92280001" style='font-weight:bold' data-seqSet={'set':'1',seq1:'foo',seq2:'bar'}>

in my script i need to get these values (set,seq1,seq2), when clicking on table row:

isSet=$(this).closest('tr').data('seqset').set;
console.log(isSet);

it gives me undefined. I need it equals 1. But when i use:

isSet=$(this).closest('tr').data('seqset');
console.log(isSet);

Then it prints whole JSON. What i missing?

3 Answers 3

4

Your attribute is not JSON. Because of that jQuery can't parse this string as JSON. Basically it checks with try-catch block, and if it's able to parse it then jQuery returns object as the result of .data call.

Make it valid JSON string then it will work:

data-seqSet='{"set": "1", "seq1": "foo","seq2": "bar"}'

Note, how attributes need to be properly quoted with ".


Source code refs:

Here is a function that is used to convert attribute string to object: https://github.com/jquery/jquery/blob/1777899a747647f3fa839eea4b0bb695d3b60f06/src/data.js#L42 (called from https://github.com/jquery/jquery/blob/1777899a747647f3fa839eea4b0bb695d3b60f06/src/data.js#L153).

1
  • It answers my question. Using the quotation marks was the issue. it needs to be mentioned that whole JSON must be enclosed in single quotes. Using double quotes for enclosing will not work because only double quotes are allowed in JSON. But i still has issue getting it work because i generated table using php echo and there are variables with quotes and its all messed up.
    – Kalle
    Commented Dec 15, 2016 at 7:42
1

As @dfsq pointed out to me jQuery .data() will parse the attribute as an object if a properly formatted JSON string is detected. So the solution is to correct your JSON formatting to wrap the key values in "

data-seqSet = {"set": "1", "seq1": "foo", "seq2": "bar"}

isSet = $(this).closest('tr').data('seqset').set;
alert(isSet);
1
  • jQuery parses strings that look like JSON (starting with { or [). So, it's not the issue. Check my answer for info what happens there.
    – dfsq
    Commented Dec 14, 2016 at 16:49
0

in php echo must be:echo "<tr id='92280001' style='font-weight:bold' data-seqSet='{\"set\":\"1\",\"seq1\":\"foo\",\"seq2\":\"bar\‌​"}'>";

Not the answer you're looking for? Browse other questions tagged or ask your own question.