1

I have a very strange issue. Im not sure why the $.data not returning the correct value after updating the data attibute even though the element has the correct value in firebug.

Demo: http://jsfiddle.net/gv5cR/

<div>
    <input type="text" name="price" id="price"/>
</div>
<button type="button" id="submit" data-price="100">Submit</button>
<div id="result"></div>
<script>
$(document).ready(function(){
    $('#price').change(function(){

        $('#submit').attr('data-price',$(this).val());

    });

    $('#submit').click(function(){
        $('#result').html($(this).data('price'));
    });

});
<script>
3
  • 1
    Why not update the data using .data() itself? Commented Mar 26, 2014 at 6:11
  • I mean $('#submit').data('price',$(this).val()); Commented Mar 26, 2014 at 6:11
  • 1
    stackoverflow.com/questions/7261619/jquery-data-vs-attr Commented Mar 26, 2014 at 6:15

5 Answers 5

1

use like

$('#submit').click(function(){
    $('#result').html($(this).attr('data-price'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

You should set data using .data()

$('#submit').data('price',$(this).val());

Demo ---> http://jsfiddle.net/gv5cR/2/

Comments

0

Since you've used .attr() to set the data-price value, you need to use .attr() instead of .data() to get that value:

$('#result').html($(this).attr('data-price'));

Updated Fiddle

Comments

0

the data-* attribute is only used to initialize the data value if not found in the internal jQuery cache... once the value is copied to jQuery data cache any change made to the attribute will not be reflected in the data value of jQuery.

If you want to update the value in the jQuery data, you will have to use the data api, instead of changing the data-* attribute.

Demo: Fiddle

Comments

0

Just use

$('#submit').click(function(){
    $(this).attr('data-price');
});

2 Comments

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Thanks @ShawnHemelstrand for the suggestion. Will try to add some explanation :)

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.