0

I'm setting an array using an HTML5 data attribute like this: <dl data-options='[{ "multiExpand": true} ]'> And grabbing it with jQuery like so: var options = $this.data('options')[0]

It works, but I'm hoping to eliminate the need for the brackets in the markup. I'm wanting to be able to write <dl data-options="multiExpand: true; otherOption: false;">

How do I need to change up the JS to grab it in that format? I've been trying .makeArray and .toJSON but they return undefined.

1 Answer 1

4

All you really need is valid JSON in the attribute, and jQuery will convert it to an object

<dl data-options='{"multiExpand":true,"otherOption":false}'>

FIDDLE

If you just have to use that invalid syntax, you have to parse it yourself, something like

var arr = $('#test').data('options').split(';').filter(Boolean),
    obj = (function() {
        var o = {};
        $.each(arr, function(_,v) {
            var parts = v.split(':');
            o[$.trim(parts[0])] = $.trim(parts[1]);
        });
        return o;
    }());

FIDDLE

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

2 Comments

Assuming your dl is as you want it: <dl data-options="multiExpand: true; otherOption: false;"> Otherwise you'll have an array with a single object inside of an object.
Thanks for this. I was hoping to not have to parse it myself (like there would be a magic jQuery method for this) but it looks like that's my only option if I want the data-options syntax without the brackets.

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.