ttmt ttmt - 4 years ago 131
Javascript Question

Store javascript variable in data attribute and retrieve it

I have a jsfiddle here - http://jsfiddle.net/0zppxL95/

I'm trying to store a jQuery variable in a html data attribute
and then get that value when I click a button.

Is it possible to do this, or how would I store a javascript variable and then retrieve it.

This will be in a loop so I wanted to store it on the variable on this object connected to the button so I can say when this button is clicked get this variable.

var test = 'Hello';

$('button').click(function(){
var output = $(this).parent().attr('data-text');
alert(output);
})

Answer Source

Set data using .data(key,value)

$(this).parent().data('text',test);

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download