dcarneiro
dcarneiro

Reputation: 7170

jQuery selector by data-id - Select many ids from an array

On a modal form that displays a list of items, I want to mark the ones that are already selected. Is there a way to select several elements at once providing an array of ids?

Example:

$('.searchable').find('[role~=item]')

returns

<tr role=​"item character" data-id=​"1">​…​</tr>​
<tr role=​"item character" data-id=​"2">​…​</tr>​
<tr role=​"item character" data-id=​"3">​…​</tr>​
<tr role=​"item character" data-id=​"4">​…​</tr>​

But i want to mark the items that are already selected adding them a "selected" class. I got the selected items in an array. Example: array = [1,3]

Is there a way to do something like this:

$('.searchable').find('[role~=item][data-id=array')

Upvotes: 0

Views: 3931

Answers (2)

adeneo
adeneo

Reputation: 318312

var Array = [1,3], 
    elems;

$.each(Array, function(i,e) {
    elems.add( $('[role~=item][data-id="'+e+'"]', '.searchable') );
});

elems.addClass('highlight');

Upvotes: 1

Adil
Adil

Reputation: 148150

You can go through array by using each and perform operation in each element in array,

 jQuery.each(array, function(i, item) {
     $(item).data("id");  
 };

or you cna try some thing like this,

var filtered = $('.searchable').find(function(){
   if(array.indexOf(this.val(), 0)
        return $(this);
});

Upvotes: 2

Related Questions