CyberJunkie
CyberJunkie

Reputation: 22674

Jquery get attribute value as it changes

I have the following HTML

<div class="element" data-settings={"apples":1,"bananas":4,"speed":300}>
</div>

The values in data-settings can be changed in my app however the js code that updates the values is written in Reactjs, is minified and unreadable. I just want to get some values using simple jquery in my own js.

In my own js, when I click .element I want to get the updated value of data-settings.

My code:

$('.element').on('click', function() {
    console.log( $(".element").data("settings") );
});

It returns the data-settings values but when I update a setting and click .element again it does not return the updated values.

For example, I update apples to 8 in my app. I see data-settings={"apples":8,"bananas":4,"speed":300} in the HTML but in my console log, apples are still 1.

I also tried:

$('body').on('click', '.element', function() {
    console.log( $(".element").data("settings") );
});

and does not work.

How can I see the live changes to the data attribute settings in my js?

Upvotes: 0

Views: 222

Answers (1)

Nishal K.R
Nishal K.R

Reputation: 1130

You should use both JSON.parse() and JSON.stringify() properties

$(document).on('click', '.show', function() {
  // Convert to JSON
  $settings = JSON.parse($(".element").attr("data-settings"));
  
  $settings.speed =  getRandomInt(500); // Update the value
  $settings.apples =  getRandomInt(10); // Update the value
  $settings.bananas =  getRandomInt(100); // Update the value
  
  // Convert to string
  $settings = JSON.stringify($settings);
  
  // Update in the Div
  $(".element").attr("data-settings",$settings);
  
  $('.result').append('<li>'+$settings+'</li>');
});


function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max) +1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element" data-settings={"apples":1,"bananas":4,"speed":300}>

Click the "Generate" button to Update the value in the Div. 
Here I added a function to generate random integer values. 

</div>

<button class="show">Show</button>

<ul class="result">
  <li>{"apples":1,"bananas":4,"speed":300}</li>
</ul>

Upvotes: 1

Related Questions