I’m storing an array in a data attribute of a button.
the array is stored successfully but for some reason every time I try to access the array stored in the data attribute, I only get the the opening brackets of array and nothing else!
it just doesn’t make sense to me…
This is my code:
var array = [{"note": "Hey I love you!",
"full_name": "Sarah James",
"date_added": "14 September 2022"
},{
"note": "Hey I love you too!",
"full_name": "Billy Smith",
"date_added": "15 September 2022"
}];
var stringed = JSON.stringify(array);
$('.o').append('<button data-test="'+stringed+'" class="viewTicketBtn">Click Here</button>');
$(document).on('click', '.viewTicketBtn', function(){
var str = $(this).attr('data-test');
console.log(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div class="o">
</div>
click on the Button and you will see the issue.
what I am doing wrong?
2
Answers
The issue is because you’re using the
data
attribute in HTML. This can only store strings. You’re correctly usingJSON.stringify()
to work around this, however the"
within the JSON are breaking the HTML format. You can escape the double quotes in the HTML, but there is an easier way.To fix the issue you can use jQuery’s
data()
method to both get and set the value, as this will retain your object structure automatically.Here’s a working example:
Use other quotes – I swapped the
'
and"
to handle the double quotes that JSON insists on.See other answer for a jQuery method of just storing the array directly in a data method