0

I use my HTML element to pass a data-attribute to jQuery but I can't seem to use that data-attribute as an option in the function:

Instead of

    var options1 = {
        series: [60, 10, 30],

I am trying to use

    <div id="evaluation" class="donut" data-series="60,10,30">

    autoValues = $('#evaluation').attr('data-series');
    const evaluation = [autoValues];

    var options1 = {
        series: evaluation,
        ...
</script>

This is returning a NaN error.

1
  • Looks like after you edited, it returns the correct records? Or you want the series data to be an array? Commented Jul 29, 2021 at 17:31

3 Answers 3

2

The attribute value is a string. You need to split the string and parse them to create a list of integers.

You can also use the .data() jQuery method to access data attributes.

autoValues = $('#evaluation').data('series');
const evaluation = autoValues.split(',').map(Number);
var options1 = {
  series: evaluation,
};

console.log(options1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="evaluation" class="donut" data-series="60,10,30">

Sign up to request clarification or add additional context in comments.

Comments

1

Data attributes are strings so you'd have to convert that string to numbers.
jQuery's .data() can parse your data attributes to data types if you specify them as json

 
 const evaluation = $('#evaluation').data('series');

 var options1 = {
     series: evaluation,
 }
 console.log(options1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="evaluation" class="donut" data-series="[60,10,30]">

Comments

0

Data attributes are essentially just strings. As such, evaluation = [autoValues] is effectively the same as evaluation = ["60,10,30"].

However, you may want to store JSON in your data attributes, because jQuery will automatically try to JSON.parse them for you if you use the data() function, i.e. $('#evaluation').data('series').

const options = {
  series: $('#evaluation').data('series')
};
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="evaluation" class="donut" data-series="[60,10,30]">

With this approach, you could even store the entire options object in a single data attribute:

const options = $('#evaluation').data('options');
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="evaluation" class="donut" data-options='{"series": [60,10,30]}'>

Comments

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.