0

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);
        })
2
  • Are you trying to assign the value of data-text to the var test when you click the button? Commented Sep 4, 2014 at 14:01
  • The jsfiddle seems to be working. What is your question? Commented Sep 4, 2014 at 14:01

3 Answers 3

2

You can do it setting the attr value and then retrieving it as you are doing now:

var test = 'Hello';

$('button').click(function(){
    //set the variable
    $(this).parent().attr('data-text', test);

    //get the variable
    var output = $(this).parent().attr('data-text');
    alert(output);
})

Living example

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

Comments

1

Set data using .data(key,value)

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

DEMO

Comments

1

For setting the data attribute you need to use:

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

Working Demo

Comments

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.