Richard Blyth
Richard Blyth

Reputation: 500

Select from a comma separated list within a data-attr

I am trying to dynamically filter a list of members who have been 'tagged' with sectors using a menu and a data-attribute (membersectors) containing the tags.

http://jsfiddle.net/richardblyth/yp8q3ewh/

The problem I am having is with the actual jQuery itself - because the data-membersectors is a comma separated list it does not seem to be selecting.

$("#js-select-sector").bind("change", function() {

  console.log((this.value));

  //Show divs with data-attr which contain the selected value
  $("div.member-small[data-membersectors*='(" + this.value + ")']").show();

  //Hide those with data-attr which do not contain the selected value
  $("div.member-small:not([data-membersectors*='(" + this.value + ")'])").hide();

});

When the user selects a sector from the menu, it should hide all which do not contain that 'tag'/sector (inside their data-membersectors)

Any pointers in the right direction would be greatly appreciated, thank you.

Upvotes: 0

Views: 1467

Answers (3)

Giannis Grivas
Giannis Grivas

Reputation: 3412

Or ...you can use .filter() like:

$("#js-select-sector").bind("change", function() {
  var val = this.value;
  $("div.member-small").filter(function() {
    $(this).attr("data-membersectors").indexOf(val) != -1 ? $(this).show() : $(this).hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Select</h1>

<select id="js-select-sector">
  <option selected="selected">Select a sector</option>
  <option value="sector1">Sector 1</option>
  <option value="sector2">Sector 2</option>
  <option value="sector3">Sector 3</option>
</select>

<h2>Results</h2>

<div class="member-small" data-membersectors="sector1">Member A</div>
<div class="member-small" data-membersectors="sector2, sector3">Member B</div>
<div class="member-small" data-membersectors="sector1, sector3">Member C</div>
<div class="member-small" data-membersectors="sector3">Member D</div>

http://jsfiddle.net/wc1k82hw/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337666

You don't need the brackets around the attribute value in the selector:

$("#js-select-sector").bind("change", function() {
    $("div.member-small").hide();
    $("div.member-small[data-membersectors*='" + this.value + "']").show();
});

Updated fiddle

Upvotes: 1

Pieter Beulque
Pieter Beulque

Reputation: 191

Why are the parentheses around this.value? This code works:

$("#js-select-sector").bind("change", function() {
    //Show divs with data-attr which contain the selected value
    $("div.member-small[data-membersectors*='" + this.value + "']").show();

    //Hide those with data-attr which do not contain the selected value
    $("div.member-small:not([data-membersectors*='" + this.value + "'])").hide();
});

Upvotes: 3

Related Questions