1

I have the following HTML generated on the server through an AJAX call. Of course there is a lot more than this but the following line is relevant:

 <div id="mydiv" DATA-mylist='[ [0,0],  [1,0],  [4,1],  [6,1],  [7,1], ]'>...</div>

I need to extract the array assigned to DATA-mylist and assign it to a property as in:

 $('#somediv').mywidget({
     prop1 : 45, //For example
     arr_prop : $('#mydiv').data('mylist') 
 });

Here arr_prop expects an array. It is not getting one. I get the following error:

  Uncaught TypeError: Cannot use 'in' operator to search for '12' in [ [0,0], ..

I tried a few things to get it to work, other than using the .attr() method instead of .data() which I think is not the right approach anyway. I am possibly missing something very basic somewhere. Please help!

3
  • 1
    check the mywidget the data part works fine jsfiddle.net/28Kzh Commented Jan 12, 2014 at 13:54
  • You are probably right. Let me look further. Upvoted your comment. Thanks. Commented Jan 12, 2014 at 14:18
  • @melc Actually no, it returns a string jsfiddle.net/28Kzh/1 Commented Jan 12, 2014 at 14:20

1 Answer 1

2

The last , in your array is the culprit:

<div id="mydiv" data-mylist="[ [0,0], [1,0], [4,1], [6,1], [7,1],]">...</div>
                                                           -----^

By adding the extra , .data() method returns a string instead of an array as it fails to parse the string, you can see the difference here.

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

7 Comments

Does not take care of my problem. I changed the server side code to reflect your suggestion and generate without that extra comma. Same error persists. It worked earlier with the same string but I was generating the entire JS on the server side and generating using .attr() to get the array string. Will look further. Your answer was helpful. Upvoting it. If that was also a problem, will accept it too later.
@Samir In which line do you get that error, can you post the related code? It seems there is also another problem.
The array I am referring to is the sortList property of tablesorter. See tablesorter.com/docs. I want to assign data-mylist value to that property. I am getting error on that line where sortList is assigned the value. If I write a static HTML with the same string/array, its fine. That is what is bugging me.
@Samir Unfortunately I haven't used tablesorter plugin so far, please check this and this.
That should do it. Thanks.
|

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.