2

I have a link and when is pressed the value of the text and data attribute of one div is changing. I have another link when is pressed i get those changed values. Here is the code:

<a class="first" href="#">change value</a>
<a class="second" href="#">get value</a>
<div class="value" data-test="test">test</div>

$(document).ready(function() {
    $('.first').on('click', function(e) {
        e.preventDefault();
        $('.value').html($(this).text()).attr('data-test',$(this).text());    
    });

    $('.second').on('click', function(e) {
        e.preventDefault();

        $value = $('.value').text();
        $data = $('.value').data('test');
        alert($data);
    });
});

http://jsfiddle.net/4daoqzc8/2/

The problem is that after value are changed i can get the new text value of the div but the value of the data attribute remains the same as was when the dom loaded. How can i get the new value of the data attribute?

Huangism
  • 16,278
  • 7
  • 48
  • 74
Nicolae
  • 52
  • 2
  • 7

4 Answers4

1

jQuery will only retrieve the data-test attribute for the value .data('test') if it hasn't stored one already. So it offers the .removeData method, which you can call when you change the attribute to force jQuery to retrieve .data('test') from the attribute again next time:

$('.value').html($(this).text())
    .removeData('test')
    .attr('data-test', $(this).text());

http://jsfiddle.net/mblase75/8mp6k2w2/


However, it would be better to just be consistent and use either .attr() or .data() to both set and get the value:

$('.value').html($(this).text())
    .data('test', $(this).text());
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
0

You can use

$data = $('.value').attr('data-test');
James Waddington
  • 2,894
  • 2
  • 15
  • 24
  • You should add an explanation about why your solution works but OP's doesn't (IIRC it's because jQuery uses it's on data store). – Max Leske Jan 22 '15 at 19:44
0

Change your code to set the value using the data function instead of attr:

$('.value').html($(this).text())
           .data('test', $(this).text()); 

Fiddle: http://jsfiddle.net/bo3h469a/

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
0

Try this.

$data = $('.value').data()['test'];

Here jQuery Data vs Attr? is more interesting topic for this.

Community
  • 1
  • 1
Lumi Lu
  • 3,289
  • 1
  • 11
  • 21