Björn Pfoster
Björn Pfoster

Reputation: 126

Access data attribute value via variable

Below, you can find a screenshot from the "selected"-Object, i am using. It is a select-list. I receive the object with following code (using jQuery):

var addArticle = $('.add-article'); // div.add-article
// selector is a dynamic value, that defines, which select-list should be "found"
var select = addArticle.find('[data-id=' + selector + ']'); 

The object-selection works fine. But when i want to get the data-attribute values (values are numbers), i fail to get them.

Object image here

i tried many variations to get the values, but here is an example of it

//$this.selectors is an array with all values beween data- and -id
$.each($this.selectors, function (i, el) {
    //return if last needed data attribute was read
    if (i == $this.lastAsInt) {
        return false;
    }
    // "generate" data-selector
    selector = '[data-' + el + '-id]';

    // select = object from the image (see link), also tried with data()
    location[el] = select.find(':selected').find(selector);
});

I hope, someone could understand my problem :)

Upvotes: 0

Views: 1846

Answers (1)

rollingthedice
rollingthedice

Reputation: 1125

Lets say you have a variable where you store your "selected" object for example var myObject

Then you can simply get the data attribute with jQuery's .data() :

myObject.data('room-id');

Here is a Fiddle

Upvotes: 1

Related Questions