0

Im trying to write a little filter script for a ajax-table and im trying to open a overlay when someone clicks on the element:

<div class="at-filter" data-filter-val="{some_value}" data-filter-type="{some_type}">
...
</div>

How do i access the data-filter-type and value via javascript/jquery? Cant find anything at all via google. Something like this is what im looking for:

this.table.find( '.at-filter' ).each(
    function(index, element) {
        var type=$(element).data-filter-type();
        var val=$(element).data-filter-val();
        self.data.filter[type] = {};
        $(element).bind('click', {self:self, val:val, type:type}, type.openContextMenu);
    }
)

edit: Mistakes were made!

Grim
  • 39
  • 11
  • @StefanR - That's a good one for doing it with the DOM (which obviously works). I'm having a surprising amount of trouble finding a *good* one using jQuery's API. I can find a lot where `attr` and/or `data` are used but the focus is different. Very surprising. – T.J. Crowder Mar 15 '19 at 10:47

2 Answers2

0

You use attr:

var type = $(element).attr("data-filter-type");

You could also use data:

var type = $(element).data("filter-type"); // Read the note below, though

... but it isn't necessary or really appropriate if all you want to do is access the values of those attributes. Contrary to popular belief, data is not an accessor for data-* attributes. (It's both more and less than that.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

To get attrbiute value use jquery attr() or in plain JavaScript getAttribute

But

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Or

In plain JavaScript setAttribute

console.log($('.me').attr('data-attribute'));
console.log($('.me').attr('data-second-attr'));

$('.me').each(function() {
  console.log(this.getAttribute('data-attribute'));
  console.log(this.getAttribute('data-second-attr'));
  this.setAttribute('data-second-attr', 'foo-bar');
  console.log('after change', this.getAttribute('data-second-attr'));
})

$('.me').prop('data-attribute', 'baz')
console.log('after change', $('.me').prop('data-attribute'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="me" data-attribute="foo" data-second-attr="bar">yo</div>
MakeLoveNotWar
  • 956
  • 9
  • 25