set HTML data attribute as an integer array

HTML code is shown below:

<div class="item_group"  data-item_ids='<%=item_ids%>'></div>

In the rendered view it appeared as below:

<div class="item_group" data-item_ids="[22, 33, 19, 21]"</div>

Why this integer array of values appeared within double quotes? So, if we take the value of this data attribute, it returns the value as string:

  item[group_id] = ($(this).attr("data-item_ids"))

 "[22, 33, 19, 21]"

How can I retrieve the value as an integer array, in order to pass the controller and get in the action as an integer array.?

Answer

Why this integer array of values appeared within double quotes?

Because that’s the type of quotes the HTML renderer uses. It’s standard to use double quotes (") to delimit attribute values in HTML, not single quotes (').

it returns the value as string. How can I retrieve the value as an integer array?

It returns a string because you’re using attr(). If you want to work with the values as an array you can call JSON.parse() on that string:

let attr = $('.item_group').attr('data-item_ids');
let arr = JSON.parse(attr);

console.log(typeof attr, attr);
console.log(typeof arr, arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item_group" data-item_ids="[22, 33, 19, 21]"></div>

Also note that you can avoid the need to manually parse the string by using jQuery’s data() method. This will automatically determine the type of the value in the data attribute and perform the type coercion for you:

let ids = $('.item_group').data('item_ids');

console.log(typeof ids, ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item_group" data-item_ids="[22, 33, 19, 21]"></div>
Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .