jQuery accessing html5 data attribute

Adam picture Adam · Jun 5, 2013 · Viewed 23.8k times · Source

On click of one of the options I am trying to get the data value from the 'ul li a' and place it into button below, I've set up a fiddle example here: http://jsfiddle.net/q5j8z/4/

But cant seem to get it working

$('ul li a').click(function(e) {
    e.preventDefault();

    var value = $(this).data();

    $('.button').data('value');
});

Does anyone have any ideas please?

Answer

palaѕн picture palaѕн · Jun 5, 2013

You can do this:

$('ul li a').click(function (e) {
    e.preventDefault();
    var value = $(this).data('value');
    $('.button').data('value', value);
    console.log($('.button').data('value'));
});

Here, $(this).data('value') is used to get the data attribute value of the link.

and $('.button').data('value', value) is used to set the data attribute value of the button.

Using, console.log($('.button').data('value')); you can check the console the data value being set.

FIDDLE DEMO

For more info:- .data() API Documentation