Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
jQuery not return updated data-value
  1. click on first green button
  2. click check price button, return right? okay
  3. click second green button, then click again check price, return wrong! why?

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).attr('data-price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</button>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Apparently, you can't mix data() and attr() functions. It is well explained in this answer: https://stackoverflow.com/a/8708345/3785618

Since .data() does extra processing jQuery stores the results of attribute evaluation in $.cache - after all, once a data attribute has been evaluated it would be wasteful to re-evaluate on every .data() call - especially since data variables can contain complex JSON strings.

Although, this will work:

$('button.setprice').click(function() {
  var txt = $(this).text();
  $('.price').text(txt).data('price', txt);
});

$('.check').on('click',function(){
  alert($('.price').data('price'))
});
.setprice {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="price"></div>

<button class="setprice">1000</button>
<button class="setprice">2000</button>
<br/>
<button class="check">check price</button>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!