0

I am working on a jQuery plugin but having some difficulty setting data on an element using jQuery.

I have the code below in an external js file.

var imgtd = $('<td></td>');
var img = $('<img src="' + imgdirectory + '16/arrow_up_green.gif" onclick="' +
    'jQuery.multiselectviewer.reOrderMultiSelectViewer(' + index + ', 1, jQuery(this)
    .data(\'multiselectEle\'));" alt="Move ' + controlName + ' up in the list">')
    .data("multiselectEle", i);
$(imgtd).append(img);
var dat = img.data();
$(row).append(imgtd);

When I set a breakpoint on the last line, I can see the data assigned to the img element but when I check the element after the page has finished loading the call the data() returns null, and when clicking on the image a null value is passed to the called function.

I imagine it is something simple that I am doing wrong but it has got me stuck.

Matthew North
  • 553
  • 5
  • 20

1 Answers1

0

When setting data-* attributes, you should consider using the attr() function as opposed to data(), as data() is better suited for actually reading the values as opposed to writing them as mentioned in this related discussion:

.attr("data-multiselectEle", i);

which appears to be working as expected as seen in the example here :

enter image description here

Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Unfortunately that is not working, I assume due to it being an object I am trying to assign. It outputs 'data-multiselectele="[object Object]"'. I need to attach the plugins options to the element so they can be accessed from within the called function. I have been looking at another plugin that does something similar and when I call the .data() function in the console on the object generated by that plugin it displays the object properties. – Matthew North Apr 14 '16 at 14:14
  • What is `i` within your context? You might have to use some of the features of the plug-in itself to target the element (and its "data") and then add your updated data to that as it sounds like you don't need a data attribute. – Rion Williams Apr 14 '16 at 14:15