Filter elements with Radiobutton in HTML and JS and Regex

Asked

Viewed 336 times

1

I have the following problem. I have 3 elements label and I want, as the option radiobutton chosen to filter them.

The problem is that when I want to filter by the name that ends in -Ivo it does not work, but the rest yes.

Here’s the HMTL code:

<p class="filters">
  <label>
    <input type="radio" name="filter" value="*" checked="checked" /> show all
  </label>
  <label>
    <input type="radio" name="filter" value="ivo" /> nome que acaba em ivo
  </label>
  <label>
    <input type="radio" name="filter" value="iva" /> nome que acaba em iva
  </label>
</p>

<div class="grid">
  <div class="element-item transition metal " data-category="transition">
    <h3 class="name">Passiva</h3>
    <p class="symbol"></p>
    <p class="number"></p>
    <p class="weight"></p>
  </div>
  <div class="element-item metalloid " data-category="metalloid">
    <h3 class="name">Passiva</h3>
    <p class="symbol"></p>
    <p class="number"></p>
    <p class="weight"></p>
  </div>
  <div class="element-item transition metal " data-category="transition">
    <h3 class="name">Agressivo</h3>
    <p class="symbol"><p>
    <p class="number"></p>
    <p class="weight"></p>
  </div>
</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<script src='http://npmcdn.com/isotope-layout@3/dist/isotope.pkgd.js'></script>

and the JS

// init Isotope
var $grid = $('.grid').isotope({
  itemSelector: '.element-item',
  layoutMode: 'fitRows'
});
// filter functions
var filterFns = {

  // show if name ends with -ium
  iva: function() {
    var name = $(this).find('.name').text();
    return name.match( /iva$/ );
  }
};

var filterFns2 = {
  sivo: function() {
      var name2 = $(this).find('.name').text();
      return name2.match( /ivo$/ );
  }
};
// bind filter on radio button click
$('.filters').on( 'click', 'input', function() {
  // get filter value from input value
  var filterValue = this.value;
  // use filterFn if matches value
  filterValue = filterFns[ filterValue ] || filterValue;
  $grid.isotope({ filter: filterValue });
});

1 answer

1

A small change in your code, and it will work perfectly, note.

// init Isotope
var $grid = $('.grid').isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows'
});

// filter functions
var filterFns = {

// show if name ends with -ium
iva: function() {
  var name = $(this).find('.name').text();
  return name.match( /iva$/ );
},

ivo: function() {
    var name2 = $(this).find('.name').text();
    return name2.match( /ivo$/ );
  }
};

// bind filter on radio button click
$('.filters').on( 'click', 'input', function() {
// get filter value from input value
var filterValue = this.value;
// use filterFn if matches value
filterValue = filterFns[ filterValue ] || filterValue;
$grid.isotope({ filter: filterValue });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.