Отфильтровать таблицу html по 2 спискам выбора

Я хотел бы отфильтровать (скрыть все, кроме выбранных) несколько записей в строках таблицы двумя списками выбора. Первый содержит страны, а второй - годы.

Я могу написать сценарий, который фильтрует по одному параметру, но как расширить функциональность, если, например, пользователь выбирает Германию и 2017 год (показать все проекты из Германии в 2017 году)?

<select class = "form-control" id = "filter-by-country">
  <option selected = "selected">COUNTRY</option>
  <option>ALL</option>
  <option>Belgium</option>
  <option>Germany</option>
  <option>Russia</option>
</select>

<select class = "form-control" id = "filter-by-year">
  <option selected = "selected">COUNTRY</option>
  <option>ALL</option>
  <option>2018</option>
  <option>2017</option>
  <option>2016</option>
  <option>2015</option>
</select>

<table class = "table table-hover all-projects">
  <thead>
    <tr>
      <th scope = "col">order date</th>
      <th scope = "col">project id</th>
      <th scope = "col">full project's name</th>
      <th scope = "col">quantity</th>
      <th scope = "col">order no</th>
    </tr>
  </thead>
  <tbody>
    <tr class = "text-center belgium 2018">
      <td>27.09.2018</td>
      <td></td>
      <td class = "text-left">First project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center germany 2017">
      <td>27.09.2017</td>
      <td>5461</td>
      <td class = "text-left">Second project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2016">
      <td>27.09.2016</td>
      <td>5462</td>
      <td class = "text-left">Third project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2018">
      <td>27.09.2018</td>
      <td>5462</td>
      <td class = "text-left">Fourth project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tbody>
</table>

Мы не можем показать вам, как расширить ваш скрипт для работы с несколькими фильтрами, не видя этого ...

Rory McCrossan 04.10.2018 13:11

Поделитесь своим кодом тем, что вы пробовали.

Jitendra G2 04.10.2018 13:13

Где твои попытки? Я не вижу никаких попыток JavaScript достичь того, что вы описываете.

Martin 04.10.2018 13:13

Нет ничего проще, чем $('tr').hide(); $('tr.germany.2017').show(); ... НО, я надеюсь, вы захотите написать хороший и поддерживаемый код. Кроме того, в ваших раскрывающихся списках отсутствуют значения параметров.

Yuri 04.10.2018 13:15

Вы можете сделать что-то вроде var data = $("#TABLEID tr." + $('#filter-by-country').val().toLowerCase() + "." + $("filter-by-year").val().toLowerCase()); $('#TABLEID').html(data); в раскрывающемся событии изменения, но вам нужно добавить условие для опции «ВСЕ» в раскрывающемся списке.

Jitendra G2 04.10.2018 13:55
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
1
5
118
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Если вы подойдете к этому с помощью KendoUI, вы можете сделать это, добавив свои данные в это, который также имеет замечательную функцию автозаполнения:

function filterAutoCompleteDataSource(e) {
  var gridFilter = e.sender.dataSource.filter();
  e.sender.element.find(".k-autocomplete input").data("kendoAutoComplete").dataSource.filter(gridFilter);
}

$(document).ready(function() {
  $("#grid").kendoGrid({
    dataSource: {
      type: "odata",
      transport: {
        read: "//demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
      },
      schema: {
        model: {
          fields: {
            OrderID: {
              type: "number"
            },
            Freight: {
              type: "number"
            },
            ShipName: {
              type: "string"
            },
            OrderDate: {
              type: "date"
            },
            ShipCity: {
              type: "string"
            }
          }
        }
      },
      pageSize: 20,
      serverPaging: true,
      serverFiltering: true,
    },
    dataBound: filterAutoCompleteDataSource,
    height: 550,
    filterable: {
      mode: "row"
    },
    pageable: true,
    columns: [{
      field: "OrderID",
      width: 225,
      filterable: {
        cell: {
          showOperators: false
        }
      }
    }, {
      field: "ShipName",
      width: 500,
      title: "Ship Name",
      filterable: {
        cell: {
          operator: "contains"
        }
      }
    }, {
      field: "Freight",
      width: 255,
      filterable: {
        cell: {
          operator: "gte"
        }
      }
    }, {
      field: "OrderDate",
      title: "Order Date",
      format: "{0:MM/dd/yyyy}"
    }]
  });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset = "utf-8" />
  <title>Kendo UI Snippet</title>

  <link rel = "stylesheet" href = "https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.common.min.css" />
  <link rel = "stylesheet" href = "https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.rtl.min.css" />
  <link rel = "stylesheet" href = "https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.silver.min.css" />
  <link rel = "stylesheet" href = "https://kendo.cdn.telerik.com/2018.3.911/styles/kendo.mobile.all.min.css" />

  <script src = "https://code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src = "https://kendo.cdn.telerik.com/2018.3.911/js/kendo.all.min.js"></script>
</head>

<body>
  <div id = "grid"></div>
</body>

</html>

Так ваша сетка, вероятно, будет даже красивее;)

Ответ принят как подходящий

который должен это сделать (совет: имена классов css не могут начинаться с цифр, это незаконно, фильтровать по значению выбранного элемента, а не по тексту)

var filter_c=$('#filter-by-country');
var filter_y=$('#filter-by-year');
$('.filter_control').on('change', function(e){

var class_c=filter_c.val().toLowerCase();
var class_y='y'+filter_y.val().toLowerCase();
$('.all-projects tr.text-center').hide();
if (class_c=='country' || class_c=='all' ){
class_c='text-center'
}
if (class_y=='yyear' || class_y=='yall' ){
class_y='text-center'
}
console.info('.'+class_c+' .'+class_y)
$('.'+class_c+'.'+class_y).show();
});

кодовое слово: https://codepen.io/peker-ercan/pen/jeqpQx

Это именно то, что мне нужно. Большое спасибо!

pobliska 04.10.2018 14:40

Этот ответ удаляет заголовок таблицы! Поскольку сейчас это принятый ответ, я надеюсь, что он будет исправлен

darklightcode 04.10.2018 14:47

Надеюсь, приведенный ниже пример будет вам полезен,

var originalContent;

$(document).ready(function() {
  originalContent = $('#allprojects').html();

  $('#filter-by-country').change(function() {
    Loaddata();
  });

  $('#filter-by-year').change(function() {
    Loaddata();
  });
});

function Loaddata() {
  $('#allprojects').html(originalContent);

  var country = $('#filter-by-country').val().toLowerCase();
  var year = $('#filter-by-year').val().toLowerCase();

  var newSelector = "";

  if (country != "all") {
    newSelector += "." + country;
  }
  if (year != "all") {
    newSelector += "." + year;
  }

  var data = $('#allprojects').find("tr" + newSelector + "");
  $('#allprojects').html(data);
}
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class = "form-control" id = "filter-by-country">
  <option>ALL</option>
  <option>Belgium</option>
  <option>Germany</option>
  <option>Russia</option>
</select>

<select class = "form-control" id = "filter-by-year">
  <option>ALL</option>
  <option>2018</option>
  <option>2017</option>
  <option>2016</option>
  <option>2015</option>
</select>

<table id='allprojects' class = "table table-hover all-projects">
  <thead>
    <tr>
      <th scope = "col">order date</th>
      <th scope = "col">project id</th>
      <th scope = "col">full project's name</th>
      <th scope = "col">quantity</th>
      <th scope = "col">order no</th>
    </tr>
  </thead>
  <tbody>
    <tr class = "text-center belgium 2018">
      <td>27.09.2018</td>
      <td></td>
      <td class = "text-left">First project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center germany 2017">
      <td>27.09.2017</td>
      <td>5461</td>
      <td class = "text-left">Second project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2016">
      <td>27.09.2016</td>
      <td>5462</td>
      <td class = "text-left">Third project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2018">
      <td>27.09.2018</td>
      <td>5462</td>
      <td class = "text-left">Fourth project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tbody>
</table>

Мой пример делает то, что вы хотите. Вы можете легко адаптировать его, если планируете добавлять фильтры как классы для строк.

$(function() {

  var selectCountry = $('#filter-by-country');
  var selectYear = $('#filter-by-year');

  var countries = [];
  var years = [];

  selectCountry
    .children('option')
    .map(function(idx, item) {
      countries.push($(item).html().toLowerCase());
    });
  selectYear
    .children('option')
    .map(function(idx, item) {
      years.push($(item).html().toLowerCase());
    })

  countries = countries.filter(function(i) {
    return ['country', 'all'].indexOf(i) === -1
  })
  years = years.filter(function(i) {
    return ['country', 'all'].indexOf(i) === -1
  })

  var tableTR = $('.all-projects tbody').find('tr');

  var filterCountries = function() {

    var country = selectCountry.children('option:selected').val().toLowerCase();
    var year = selectYear.children('option:selected').val().toLowerCase();

    var conditionHappens = false;
    var foundCountry = countries.indexOf(country) !== -1;
    var foundYear = years.indexOf(year) !== -1;
    var conditions = [];

    if (foundCountry) {
      conditions.push(country);
    }

    if (foundYear) {
      conditions.push(year);
    }

    $.each(tableTR, function(idx, item) {

      var processCond = conditions.map(function(cond) {
        return $(item).hasClass(cond);
      }).indexOf(false) === -1;

      if (processCond) {
        $(item).show();
      } else {
        $(item).hide();
      }

    })

  }

  $(selectCountry).on('change', filterCountries)
  $(selectYear).on('change', filterCountries)

})
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- COUNTRIES -->
<select class = "form-control" id = "filter-by-country">
  <option selected = "selected">COUNTRY</option>
  <option>ALL</option>
  <option>Belgium</option>
  <option>Germany</option>
  <option>Russia</option>
</select>

<!-- YEARS -->
<select class = "form-control" id = "filter-by-year">
  <option selected = "selected">COUNTRY</option>
  <option>ALL</option>
  <option>2018</option>
  <option>2017</option>
  <option>2016</option>
  <option>2015</option>
</select>

<table class = "table table-hover all-projects">
  <thead>
    <tr>
      <th scope = "col">order date</th>
      <th scope = "col">project id</th>
      <th scope = "col">full project's name</th>
      <th scope = "col">quantity</th>
      <th scope = "col">order no</th>

    </tr>
  </thead>
  <tbody>
    <tr class = "text-center belgium 2018">
      <td>27.09.2018</td>
      <td></td>
      <td class = "text-left">First project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center germany 2017">
      <td>27.09.2017</td>
      <td>5461</td>
      <td class = "text-left">Second project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2016">
      <td>27.09.2016</td>
      <td>5462</td>
      <td class = "text-left">Third project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tr class = "text-center russia 2018">
      <td>27.09.2018</td>
      <td>5462</td>
      <td class = "text-left">Fourth project</td>
      <td>0</td>
      <td></td>
    </tr>
    <tbody>
</table>

Другие вопросы по теме