Charles Okwuagwu Charles Okwuagwu - 5 months ago 14
jQuery Question

How do I filter list of items having data-rel tags

How can we use jQuery to filter the list of items below based on selected option from drop-down list?

Each of the items has a data-rel tag

<select id="lstkbCategory" data-placeholder="Choose a Category">
<option> --show all-- </option>
<option>close</option>
<option>general</option>
<option>verification</option>
<option>welcome</option>
</select>
<br>
<div class="kb-items">
<a class="kb-item" href="#" data-rel="verification">xxx</a>
<a class="kb-item" href="#" data-rel="close">xxx</a>
<a class="kb-item" href="#" data-rel="welcome">444</a>
<a class="kb-item" href="#" data-rel="welcome">aaa</a>
<a class="kb-item" href="#" data-rel="general">bbb</a>
<a class="kb-item" href="#" data-rel="general">ggg</a>
<a class="kb-item" href="#" data-rel="general">qqq</a>
<a class="kb-item" href="#" data-rel="general">sos</a>
</div>

Answer

$('#lstkbCategory').change(function() {

  var value = $('option:selected', this).text();//get the text of selected option

  $('.kb-items a').filter(function(i, v) {
    $(v).removeClass('red')
    return $(v).attr('data-rel') == value//compare the option with the data-rel



  }).addClass('red')//addClass to anchor with matching data-rel to value

})
.red {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="lstkbCategory" data-placeholder="Choose a Category">
  <option>--show all--</option>
  <option>close</option>
  <option>general</option>
  <option>verification</option>
  <option>welcome</option>
</select>
<br>
<div class="kb-items">
  <a class="kb-item" href="#" data-rel="verification">xxx</a>
  <a class="kb-item" href="#" data-rel="close">xxx</a>
  <a class="kb-item" href="#" data-rel="welcome">444</a>
  <a class="kb-item" href="#" data-rel="welcome">aaa</a>
  <a class="kb-item" href="#" data-rel="general">bbb</a>
  <a class="kb-item" href="#" data-rel="general">ggg</a>
  <a class="kb-item" href="#" data-rel="general">qqq</a>
  <a class="kb-item" href="#" data-rel="general">sos</a>
</div>