18

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 JS fiddle example here:

https://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');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul>
    <li><a data-value="50" href="#">Option 1</a></li>
    <li><a data-value="40" href="#">Option 2</a></li>
    <li><a data-value="10" href="#">Option 3</a></li>
</ul>

<a data-value="" class="button" href="">Go</a>

Does anyone have any ideas please?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Adam
  • 812
  • 3
  • 13
  • 22

6 Answers6

16

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

palaѕн
  • 72,112
  • 17
  • 116
  • 136
2

Use it like this:

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

And then:

$('.button').data('value', value);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

Try this:

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

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

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

You can see the value of the button with console.log into your console with:

console.log('data: '+$(".button").data("value"));
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
1

You are not assigning the value data to the button actually. Try this:

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

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

    // assign the value form the clicked anchor to button value data
    $('.button').data('value', value);

    console.log($('.button').data('value'));
});
thomas
  • 2,580
  • 1
  • 22
  • 28
0

First off you are are you trying to insert the value of variable value or 'value' literal?

data() is meant to be used similarily to attr('attr-name', attr_value) like below:

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

The above works in your fiddle.

Ted
  • 3,985
  • 1
  • 20
  • 33
0

You don't need to specify a data- prefix because jQuery does that automatically.

So ensure you are using the right attribute for the value, as below:

$('ul li a').click(function(e) {
    e.preventDefault();
    var value = $(this).data('value');
    $('.button').data('value', value);
});
TylerH
  • 20,799
  • 66
  • 75
  • 101
Emeka Mbah
  • 16,745
  • 10
  • 77
  • 96