0

I have a habit of using lots of data tags, and then reading them one at a time in jQuery e.g.

*html*
<span data-group="1" data-item="2" data-user="abc" data-type="4" . . . . . </span>

*jQuery*
getItemSelected = function($in){dataItem=$in.data("item");}

But I'm wondering if there may be a better way than creating an ever increasing number of data tags, by using one tag with json as the content. But so far all my attempts at this have failed.

I'm thinking something like the following:

*html*
<span data-options='[{"group":"1","item":"2","user":3". . . .}]'></span>

*jQuery*
getOptions = function($in)
{
dataOptions=jQuery.parseJSON( $in.data("options") );
alert(dataOptions === "group");
}

But every variation I have tried so far simply comes up as undefined. What is the correct way of doing this?

2
  • 1
    Try $in.data("options")[0].group. You've made your JSON represent an array by using [ and ]. Also, jQuery's data function will automatically parse JSON in data- attributes Commented Aug 24, 2020 at 14:59
  • 1
    <span data-options='{"group":"1","item":"2","user":3". . . .}'></span> Commented Aug 24, 2020 at 15:01

2 Answers 2

1

If all you want to transfer are multiple distinct single values (like a group, item, user, type), the JSON should be just an object rather than an array of objects.

Also, rather than putting everything into an attribute, you may find it easier to manage to put it as the text content of an invisible tag, like a non-runnable <script> tag:

const data = JSON.parse(document.querySelector('#data-tag').textContent);
console.log(
  data.group,
  data.user
);
<script type="application/json" id="data-tag">
{"group":"1","item":"2","user":"3"}
</script>

No jQuery needed.

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

Comments

0

If a data attribute contains valid json, jQuery data() will automatically parse it for you.

$('span[data-options]').each(function(){
    const opts = $(this).data('options');        
    console.log('Type:', typeof opts)
    console.log(opts);
    console.log( '-----------');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-options='{"group":"1","item":"2","user":"3"}'></span>
<span data-options='{"group":"2","item":"3","user":"4"}'></span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.