Tintin81
Tintin81

Reputation: 10215

How to filter options by data-attribute with jQuery?

I have a select box with various options:

<select id="person">
  <option data-project_ids=​"11 23 19" value=​"17">​Goodwin, Alisha​</option>​
  <option data-project_ids=​"16" value=​"20">​Ratke, Danny​</option>​
  <option data-project_ids=​"" value=​"16">​Powlowski, Ron​</option>​
  <option data-project_ids=​"19 7" value=​"20">​Ratke, Danny​</option>​
</select>

How can I filter the options by a data-project_id?

Right now I have:

var project = 19; // just an example
$('#person').html().filter('[data-project_ids="' + project + '"]');

This would work if every option had only one data-project_id. However, there are often many, sometimes none at all.

Thanks for any help.

Upvotes: 2

Views: 2297

Answers (3)

Mehran Hatami
Mehran Hatami

Reputation: 12961

if you do:

$("#person [data-project_ids*=19]")

it would even select data-project_ids=192, but you can do this instead:

$("#person [data-project_ids~=19]")

~= is jQuery's attribute-contains-word selector:

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

Upvotes: 6

charlietfl
charlietfl

Reputation: 171690

I would suggest reformatting your space separated string values to array syntax. jQuery.data will automatically read as array

A big advantage to this over the using contains selectors is precision. You will only get return when values are identical, contains selectors will return partial matches also.

<option data-project_ids=​"[11,23,19]" value=​"17">​Goodwin, Alisha​</option>

Then filter can be like:

var project = 19
$('#person option').filter(function(){
   return $.inArray(project, $(this).data('project_ids')) > -1
});

Will be easy to add or remove ID's using conventional array methods (push, splice etc)

DEMO

Upvotes: 6

James Lai
James Lai

Reputation: 2071

$("#person [data-project_ids*=19]") should work.

Upvotes: 0

Related Questions