#javascript #html #jquery #filtering
#javascript #HTML #jquery #фильтрация
Вопрос:
Я хочу отфильтровать эту таблицу с помощью ОБЕИХ кликабельных кнопок «и «поиск по вводу. У меня есть группа кнопок, где каждая кнопка имеет событие onclick для фильтрации строк, а поиск фильтрует строки с помощью функции keyup. Каждый из них работает отдельно, но я бы хотел, чтобы они работали вместе.
1.Нажмите кнопку (строки отфильтрованы).
2. Добавьте текстовый поиск (видимые строки снова отфильтрованы).
или наоборот, или просто шаг 1 или шаг 2
СКРИПКА http://jsfiddle.net/rbla/Lh3kpxg2/29 /
var $rowsss = $('#table tr:visible');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ /g, ' ').toLowerCase();
$rowsss.show().filter(function() {
var text = $(this).text().replace(/s /g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
$("#all").click(function() {
var rows = $("#table").find("tr").show();
});
$("#green").click(function() {
var rows = $("#table").find("tr").hide();
rows.filter(":contains('Green')").show();
});
$("#orange").click(function() {
var rows = $("#table").find("tr").hide();
rows.filter(":contains('Orange')").show();
});
$("#lemon").click(function() {
var rows = $("#table").find("tr").hide();
rows.filter(":contains('Lemon')").show();
});
body {
padding: 20px;
}
input {
margin-bottom: 5px;
padding: 2px 3px;
width: 209px;
margin-top: 5px;
}
td {
padding: 4px;
border: 1px #CCC solid;
width: 100px;
}
.buttons-wrapper {
clear: both;
display: inline-block;
box-sizing: border-box;
margin: 0 1%;
}
.my-radio-button {
position: absolute;
left: -9999em;
top: -9999em;
}
.my-radio-button label {
float: left;
padding: .5em 1em;
cursor: pointer;
border: 1px solid #28608f;
margin-right: -1px;
color: #fff;
/* background-color: #428bca; */
background-color: blue;
font-family: 'Montserrat', sans-serif;
font-size: 11px;
/* text-transform: uppercase; */
}
.my-radio-button label:first-of-type {
border-radius: .7em 0 0 .7em;
}
.my-radio-button label:last-of-type {
border-radius: 0 .7em .7em 0;
}
.my-radio-button:checked label {
/* background-color: #3277b3; */
background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="buttons-wrapper">
<input type="radio" class="my-radio-button" name="radioButtonTest" value="1" id="all" checked />
<label for="all">All</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="2" id="green" />
<label for="green">Green</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="3" id="orange" />
<label for="orange">Orange</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="4" id="lemon" />
<label for="lemon">Lemon</label>
</div><br clear="all">
<input type="text" id="search" placeholder="Type to search">
<table id="table">
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
</table>
Ответ №1:
Этот код теперь
- обрабатывает пробел / пустое поле
- обрабатывает нажатие кнопки при заполнении поля поиска
- поиск будет удален, если вы нажмете все
- довольно СУХОЙ
Вы можете избавиться от функции titleCase, если измените идентификаторы кнопок, чтобы они совпадали со вторым столбцом, или если вы измените второй столбец, чтобы он имел идентификатор в нижнем регистре в качестве атрибута
const count = () => {
$("#count").text($("#table tbody tr:visible").length);
};
const titleCase = val => val.slice(0, 1).toUpperCase() val.slice(1);
$(function() {
$('#search').on("input", function() {
const val = $(this).val().replace(/ /g, ' ').trim().toLowerCase();
const but = titleCase($(".my-radio-button:checked").attr("id"));
if (val === "" amp;amp; but === "all") {
$('#table tr').show();
count();
return;
}
$('#table tr').each(function() {
const found = $(this).text().replace(/s /g, ' ').toLowerCase().indexOf(val) != -1;
let show = (but === "All" amp;amp; found) || ($(this).filter(":contains(" but ")").length > 0 amp;amp; found)
$(this).toggle(show);
})
count()
});
$(".my-radio-button").on("click", function() {
if (this.id === "all") {
$("#table tr").show();
$('#search').val(""); // Clear input on click of ALL
} else {
const rows = $("#table").find("tr").hide();
const val = titleCase(this.id);
rows.filter(":contains(" val ")").show();
$('#search').trigger("input");
}
count();
});
count();
$("#total").text($("#table tbody tr").length);
}); // end of $(function() {
body {
padding: 20px;
}
input {
margin-bottom: 5px;
padding: 2px 3px;
width: 209px;
margin-top: 5px;
}
td {
padding: 4px;
border: 1px #CCC solid;
width: 100px;
}
.buttons-wrapper {
clear: both;
display: inline-block;
box-sizing: border-box;
margin: 0 1%;
}
.my-radio-button {
position: absolute;
left: -9999em;
top: -9999em;
}
.my-radio-button label {
float: left;
padding: .5em 1em;
cursor: pointer;
border: 1px solid #28608f;
margin-right: -1px;
color: #fff;
/* background-color: #428bca; */
background-color: blue;
font-family: 'Montserrat', sans-serif;
font-size: 11px;
/* text-transform: uppercase; */
}
.my-radio-button label:first-of-type {
border-radius: .7em 0 0 .7em;
}
.my-radio-button label:last-of-type {
border-radius: 0 .7em .7em 0;
}
.my-radio-button:checked label {
/* background-color: #3277b3; */
background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="buttons-wrapper">
<input type="radio" class="my-radio-button" name="radioButtonTest" value="1" id="all" checked />
<label for="all">All</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="2" id="green" />
<label for="green">Green</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="3" id="orange" />
<label for="orange">Orange</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="4" id="lemon" />
<label for="lemon">Lemon</label>
</div><br clear="all">
<input type="text" id="search" placeholder="Type to search" autocomplete="off"> <span id="count"></span>/<span id="total"></span>
<table id="table">
<thead>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tbody>
<tfoot>
</tfoot>
</table>
Комментарии:
1. нажмите зеленый, а затем нажмите все — все строки будут скрыты
2. введите что-то в поиске, а затем верните это обратно — не вернет все строки
3. Хорошо, теперь это обрабатывает пробел и щелчок по кнопкам во время поиска и щелчка по всем
4. Сейчас я нажимаю на кнопки, и ничего не происходит — вот ваш код — jsfiddle jsfiddle.net/rbla/4wo3z7ur/7
5. Я хотел бы учитывать все сценарии и комбинации — нажмите или выполните поиск, может быть, 1, может быть, оба .. спасибо
Ответ №2:
Отредактированный только JavaScript:
var $rowsss = $('#table tr:visible');
const $search = $('#search');
let groupFilter = 'all';
const searchAll = () => {
var val = $.trim($search.val()).replace(/ /g, ' ').toLowerCase();
$rowsss.show().filter(function() {
var text = $(this).text().replace(/s /g, ' ').toLowerCase();
const hasGroup = groupFilter == 'all' || text.indexOf(groupFilter) >= 0;
const notHasSearch = !~text.indexOf(val);
return !hasGroup || notHasSearch;
}).hide();
return true;
}
$search.keyup(() => searchAll());
$(".my-radio-button").click(function() {
groupFilter = this.id;
searchAll()
});
body {
padding: 20px;
}
input {
margin-bottom: 5px;
padding: 2px 3px;
width: 209px;
margin-top: 5px;
}
td {
padding: 4px;
border: 1px #CCC solid;
width: 100px;
}
.buttons-wrapper {
clear: both;
display: inline-block;
box-sizing: border-box;
margin: 0 1%;
}
.my-radio-button {
position: absolute;
left: -9999em;
top: -9999em;
}
.my-radio-button label {
float: left;
padding: .5em 1em;
cursor: pointer;
border: 1px solid #28608f;
margin-right: -1px;
color: #fff;
/* background-color: #428bca; */
background-color: blue;
font-family: 'Montserrat', sans-serif;
font-size: 11px;
/* text-transform: uppercase; */
}
.my-radio-button label:first-of-type {
border-radius: .7em 0 0 .7em;
}
.my-radio-button label:last-of-type {
border-radius: 0 .7em .7em 0;
}
.my-radio-button:checked label {
/* background-color: #3277b3; */
background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="buttons-wrapper">
<input type="radio" class="my-radio-button" name="radioButtonTest" value="1" id="all" checked />
<label for="all">All</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="2" id="green" />
<label for="green">Green</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="3" id="orange" />
<label for="orange">Orange</label>
<input type="radio" class="my-radio-button" name="radioButtonTest" value="4" id="lemon" />
<label for="lemon">Lemon</label>
</div><br clear="all">
<input type="text" id="search" placeholder="Type to search">
<table id="table">
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Blue</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
<tr>
<td>Apple</td>
<td>Green</td>
</tr>
<tr>
<td>Grapes</td>
<td>Green</td>
</tr>
<tr>
<td>Orange</td>
<td>Orange</td>
</tr>
<tr>
<td>Lemon</td>
<td>Black</td>
</tr>
</table>
Ответ №3:
Попробуйте использовать этот код, который я нашел на других форумах:
<form class="filter-form" action="">
<div class="input-field">
<div class="accessories-display-subtitle"><h2>BRANDS</h2><div class="divider"></div></div>
<div class="input-field-content">
<div class="checkbox-div"><input type="checkbox" name="brand" value="raleigh" id="raleigh"><label for="raleigh">Raleigh</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="focus" id="focus"><label for="focus">Focus</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="felt" id="felt"><label for="felt">Felt</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="specialized" id="specialized"><label for="specialized">Specialized</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="trek" id="trek"><label for="trek">Trek</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="pinarello" id="pinarello"><label for="pinarello">Pinarello</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="bmc" id="bmc"><label for="bmc">BMC</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="giant" id="giant"><label for="giant">Giant</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="salsa" id="salsa"><label for="salsa">Salsa</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="cannondale" id="cannondale"><label for="cannondale">Cannondale</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="cervelo" id="cervelo"><label for="cervelo">Cervelo</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="bianchi" id="bianchi"><label for="bianchi">Bianchi</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="trinx" id="trinx"><label for="trinx">Trinx</label></div>
<div class="checkbox-div"><input type="checkbox" name="brand" value="spanker" id="spanker"><label for="spanker">Spanker</label></div>
</div>
</div>
<div class="input-field">
<div class="accessories-display-subtitle"><h2>PRICE RANGE</h2><div class="divider"></div></div>
<div class="input-field-content">
<div class="checkbox-div"><input type="checkbox" name="price" value="6-7k" id="6-7k"><label for="6-7k">₱6000 - ₱7000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="8-9k" id="8-9k"><label for="8-9k">₱8000 - ₱9000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="10-20k" id="10-20k"><label for="10-20k">₱10000 - ₱95000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="20-40k" id="20-40k"><label for="20-40k">₱95000 - ₱40000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="40-60k" id="40-60k"><label for="40-60k">₱40000 - ₱60000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="60-80k" id="60-80k"><label for="60-80k">₱60000 - ₱80000</label></div>
<div class="checkbox-div"><input type="checkbox" name="price" value="80upk" id="80upk"><label for="80upk">₱80000 and higher</label></div>
</div>
</div>
<div class="input-buttons">
<input type="submit" value="Filter" name="filter">
<input type="reset" value="Reset" name="reset">
</div>
</form>
<div class="flowers">
<div class="flower" data-id="aloe" data-category="giant trinx">Aloe</div>
<div class="flower" data-id="lavendar" data-category="purple green medium africa europe">Lavender</div>
<div class="flower" data-id="stinging-nettle" data-category="green large africa europe asia">Stinging Nettle</div>
<div class="flower" data-id="gorse" data-category="green yellow large europe">Gorse</div>
<div class="flower" data-id="hemp" data-category="green large asia">Hemp</div>
<div class="flower" data-id="titan-arum" data-category="purple other giant asia">Titan Arum</div>
<div class="flower" data-id="golden-wattle" data-category="green yellow large australasia">Golden Wattle</div>
<div class="flower" data-id="purple-prairie-clover" data-category="purple green other medium north-america">Purple Prairie Clover</div>
<div class="flower" data-id="camellia" data-category="pink other large north-america">Camellia</div>
<div class="flower" data-id="scarlet-carnation" data-category="red medium north-america">Scarlet Carnation</div>
<div class="flower" data-id="indian-paintbrush" data-category="red medium north-america">Indian Paintbrush</div>
<div class="flower" data-id="moss-verbena" data-category="purple other small south-america">Moss Verbena</div>
<div class="flower" data-id="climbing-dayflower" data-category="blue tiny south-america">Climbing Dayflower</div>
<div class="flower" data-id="antarctic-pearlwort" data-category="green yellow large antarctica">Antarctic Pearlwort</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>var $filterCheckboxes = $('input[type="checkbox"]');
$filterCheckboxes.on('change', function() {
var selectedFilters = {};
$filterCheckboxes.filter(':checked').each(function() {
if (!selectedFilters.hasOwnProperty(this.name)) {
selectedFilters[this.name] = [];
}
selectedFilters[this.name].push(this.value);
});
var $filteredResults = $('.flower');
$.each(selectedFilters, function(name, filterValues) {
$filteredResults = $filteredResults.filter(function() {
var matched = false,
currentFilterValues = $(this).data('category').split(' ');
$.each(currentFilterValues, function(_, currentFilterValue) {
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
return matched;
});
});
$('.flower').hide().filter($filteredResults).show();
});
</script>