1

I have the following piece of code which fires on click of a button with class undo. Here variable cls gives outputs a3, a2 etc. as expected, but when I use cls in

var some = $("path#path"+cls_id).data("id").cls ; ,

I get alert result as undefined. But when I replaced cls with a3 or a2 manually, got the result. Complete code:

$('body').on('click','.undo',function () { 
    var cls_id = $(this).parent().attr('class');
    var cls = $(this).attr('data-undo');
    var some = $("path#path"+cls_id).data("id").cls;
    alert(some);
});

HTML

<path id="path1" stroke="rgb(178, 34, 34)" stroke-width="2" fill="none" d="M683 137 L742 217 L535 301 L513 220" data-id="{ "a1":"L33 24", "a2":"L442 89" }"></path>

Somebody please suggest a way to fix the issue.

arshad
  • 883
  • 7
  • 30

2 Answers2

0

If you have defined the element as follow

<div class="test" data-id-cls="me"></div>

Then you should access it as follows

var some = $(".test").data("idCls");

Note the "C" in cls it`s in capital

Madhu
  • 2,416
  • 3
  • 15
  • 33
0

I guess the problem is with the selector path, because there is no element path defined in HTML. Since you already use an id selector #path..., there is also no need to further restrict the selector.

Simply using the id selector should be sufficient, e.g.

var some = $("#path"+cls_id).data("id").cls;

When you look at the data-id attribute, you will see problems with the quoting.

data-id="{ "a1":"L33 24", "a2":"L442 89" }"

When you change the enclosing double quotes to single quotes, you are one step nearer to the solution, e.g.

data-id='{ "a1":"L33 24", "a2":"L442 89" }'

This will give you the object, you are looking for. The second part is adding a cls attribute of course. The missing attribute is the reason, why a1 or a2 work, but cls doesn't

data-id='{ "a1":"L33 24", "a2":"L442 89", "cls": "some value" }'

When cls is not the name itself, but contains the name of the attribute, i.e. a1 or a2, you must access the value with bracket notation

var some = $("#path"+cls_id).data("id")[cls];

or

var obj = $("#path"+cls_id).data("id");
var some = obj[cls];

See also MDN - Working with objects

Community
  • 1
  • 1
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
  • actually I have a `path` in my html. And I have tested by removing the first `path` from `path#path`, but the result is same. – arshad Mar 14 '15 at 13:36
  • `cls` is not a value inside `data-id`, but `cls` contains a value(eg: a1 or a2 etc.) which is substituted at the end of `var some = $("path#path"+cls_id).data("id").cls;` , which is actually not getting replaced. – arshad Mar 15 '15 at 17:18
  • The last part of the answer(bracket notation) helped. Could you please modify your answer so that I can accept it? – arshad Mar 16 '15 at 04:13