0

I'm having several elements on my page with the same data attribute, although different values. The elements are formatted like so:

<input type="radio" data-toggle='["one","two","three"]'/>

Now, I want to get the data from all those elements, and I thought I could just do:

var data = $('[data-toggle]').data("toggle");

But this only outputs the data from the first element, all other elements with that data-attribute is ignored.

I'm guessing this has to do with it beeing arrays/JSON formatted, but I'm not clear about why this is the case, and how I should go about retrieving all my values.

How can I get all data from all those data attributes?

Here is a fiddle illustrating my problem: http://jsfiddle.net/6u67o9oo/

1 Answer 1

6

You'd have to iterate over each element:

$('[data-toggle]').each(function() {
    var data = $(this).data("toggle");

    //Do stuff
});

Or you could use .map to get a 2D array of all the data-toggle attributes:

var newArray = $('[data-toggle]').map(function() {
    return $(this).data("toggle");
}).get();
Sign up to request clarification or add additional context in comments.

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.