1

I'm trying to grab out an array from a data attribute on a table row.

When I run this it returns an array of objects in which I can view there data attributes

$('#searchresultstable input[type=checkbox]:checked').closest('tr')

Chrome's response:

[
    <tr class=​"mediafilter-1" data-titleid=​"794">​…​</tr>​,
    <tr class=​"mediafilter-1" data-titleid=​"891">​…​</tr>​, 
    <tr class=​"mediafilter-1" data-titleid=​"1127">​…​</tr>​,
    <tr class=​"mediafilter-1" data-titleid=​"1388">​…​</tr>
​]

How ever when I add the data attribute function:

$('#searchresultstable input[type=checkbox]:checked').closest('tr').data('titleid')

Chrome Response: 794

I know I could probably loop through these with an each and grab then out. However, I'd like to know how to do this the short hand way, with out the explicit each. Does anybody know how to grab out these values?

3
  • 3
    You'll have to use an each, or loop of some variety. When you use data on a selector containing multiple elements only the first element will be read. Commented Jan 23, 2015 at 15:04
  • What do you think the cleanest way to do that would be then? The map function? Commented Jan 23, 2015 at 15:06
  • If you're happy to have the values in an array, then yes. Commented Jan 23, 2015 at 15:07

1 Answer 1

8

You can map it like this:

var datasArray = $('#searchresultstable input[type=checkbox]:checked').closest('tr').map(function(){
     return this.dataset.titleid;// or $(this).data('titleid')
}).get();
Sign up to request clarification or add additional context in comments.

3 Comments

this.dataset won't work in IE < 11, it would be safer to use the jQuery provided to ensure cross browser support
Why the .get() at the end?
Notice the .get() chained at the end. .map() actually returns a jQuery-wrapped collection, even if we return strings out of the callback. We need to use the argument-less version of .get() in order to return a basic JavaScript array that we can work with. source: learn.jquery.com/using-jquery-core/iterating