Фильтр таблицы
Вложений: 3
Друзья, вот такой код фильтра. Он делает поиск по ячейкам таблицы начиная со второго столбца по четвертый в зависимости от введенного значения. Если ввели 40, он показывает tr, где есть числа 40 и больше. Но проблема в том, что другие tr он скрывает. Как сделать чтобы при вводе числа в input, фильтр искал значение и выводил 4 строки, то есть не скрывал название команд и строки HG и TL и наоборот если нашел значение в HG и не скрывал 1х2 и TL. На картинке мы ввели 40, в первой строке он найдет значение 40, но 3 другие строки скрыл. Как сделать чтоб он оставил все 4 строки? С учетом что в таблице таких tr очень много, то есть 4 строки это как один блок информации. 4 tr с каждым своим классом. Надеюсь не сильно запутал:)
$(function() {
$("#cf_1x2").on("input", function() {
var val = +this.value.trim();
$.each($("#t tbody tr"), function(i, tr) {
var td = [].filter.call(tr.querySelectorAll("td:nth-child(n + 2):nth-child(-n + 4)"), function(td) {
var num = td.textContent.match(/\d+(.\d+)?(?=\s*%)/);
var ok = isNaN(val) || num !== null && val < +num[0]
$(td).toggleClass("", ok)
return ok;
});
$(this).toggle(!!td.length);
});
});
});
<div class="form-group"> <input type="text" class="form-control pull-right" id="cf_1x2" placeholder="Движение 1X2 от %" style="width: 100%;"> </div> <table class="simple" id="t"> <tr class="team"> <td>00:30</td> <td style="color:#666;text-align: left;font-weight: 600;"> <small style="color:black;font-weight: 600;"> <span>Conmebol - Sudamericano U20</span> </small> <br>Brazil U20 - Venezuela U2</td> <td style="color:#666;text-align: left;font-weight: 600;"></td> <td style="color:#666;text-align: left;font-weight: 600;"></td> <td rowspan="4" style="color:green;font-weight: 600;> <span style=" color:black;"="">2 - 1 <small> <br>1 - 0</small></td> </tr> <tr class="1x2"> <td>1X2</td> <td class="yes_volume_cf" style="color:green;font-weight: 600;"> <span style="color:black;">1.8</span> <small style="color:red;"> <br>(1.66) 8%</small> </td> <td class="" style="color:green;font-weight: 600;"> <span style="color:black;">3.5</span> <small style="color:green;"> <br>(3.6) 3%</small></td> <td class="" style="color:green;font-weight: 600;"> <span style="color:black;">3.6</span> <small style="color:green;"> <br>(5.25) 46%</small></td> </tr> <tr class="handicap"> <td>HG</td> <td class="yes_volume_cf" style="color:green;font-weight: 600;"> <span style="color:black;">1.92</span> <small style="color:red;"> <br>(1.87) 3%</small></td> <td style="color:green;font-weight: 600;"> <span style="color:black;">0.5</span> <small style="color:black;"> <br>(0.5)</small></td> <td class="" style="color:green;font-weight: 600;"> <span style="color:black;">1.88</span> <small style="color:green;"> <br>(1.92) 2%</small></td> </tr> <tr class="total"> <td>TL</td> <td class="" style="color:green;font-weight: 600;"> <span style="color:black;">2.02</span> <small style="color:red;"> <br>(1.8) 11%</small></td> <td style="color:green;font-weight: 600;"> <span style="color:black;">2.5</span> <small style="color:red;"> <br>(2)</small></td> <td class="yes_volume_cf" style="color:green;font-weight: 600;"> <span style="color:black;">1.78</span> <small style="color:green;"> <br>(2) 12%</small></td> </tr> http://www.fotolink.su/v.php?id=6d8e...3a3b6862c2714b http://www.fotolink.su/v.php?id=90ff...0b9517c4482aca http://www.fotolink.su/v.php?id=b694...f0c8865aa878bc |
Цитата:
|
Эти группы по четыре строчки нужно заключить в <TBODY>, тогда вы сможете делать поиск по группам, и скрывать/показывать именно группы целиком. Т. е. у вас структура будет не как на 3-ей картинке, а вот так...
<table> <thead> <th>22.01</th> <th>Команды</th> <th>1</th> <th>X</th> <th>2</th> </thead> <tbody> <tr class="team"></tr> <tr class="1x2"></tr> <tr class="handicap"></tr> <tr class="total"></tr> </tbody> <tbody> <tr class="team"></tr> <tr class="1x2"></tr> <tr class="handicap"></tr> <tr class="total"></tr> </tbody> <tbody> <tr class="team"></tr> <tr class="1x2"></tr> <tr class="handicap"></tr> <tr class="total"></tr> </tbody> </table> |
Malleys,
:victory: |
Сделал как вы сказали
Сделал как вы сказали, но опять он скрывает все 3 строчки. Мне кажется, в самом фильтре что то не то. Уже третий день бьюсь:(
http://www.fotolink.su/v.php?id=5285...36ef4c25d2778d Цитата:
|
Проблема заключается в
Вложений: 1
Проблема заключается в том, что при вводе значения в input, фильтр находит эту строку, но 3 других он скрывает, а должно быть как бы блоком из 4 строк.
|
Если я вас правильно понял, то так...
$(function() {
$("#cf_1x2").on("input", function() {
var value = +this.value.trim();
$.each($("#t tbody"), function(i, tBody) {
var ok = Array.from(tBody.rows).some(function(td, index) {
var match = td.textContent.match(/\d+(.\d+)?(?=\s*%)/g);
if(match)
return match.map(Number).some(function(p) { return value <= p; })
});
$(tBody).toggle(ok);
});
});
});
|
denis_kontarev,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
.ok{
background-color: #228B22;
color: #FFFFFF;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$("#cf_1x2").on("input", function() {
var val = this.value.trim();
$.each($("#t tbody"), function(i, tbody) {
var tds = $("td", tbody).filter(function(i, td) {
var num = td.textContent.match(/\d+(.\d+)?(?=\s*%)/);
var ok = false;
if(val && num != null){
ok = !isNaN(+val) && +val < +num[0];
};
$(td).toggleClass("ok", ok);
return ok || !val;
});
$(this).toggle(!!tds.length);
});
});
});
</script>
</head>
<body>
<input type="text" class="form-control pull-right" id="cf_1x2" placeholder="Движение 1X2 от %" style="width: 100%;">
<table id="t">
<thead>
<th>22.01</th>
<th>Команды</th>
<th>1</th>
<th>X</th>
<th>2</th>
</thead>
<tbody>
<tr class="team"><td>70%</td></tr>
<tr class="1x2"><td>1</td></tr>
<tr class="handicap"><td>2</td></tr>
<tr class="total"><td>3</td></tr>
</tbody>
<tbody>
<tr class="team"><td>40%</td></tr>
<tr class="1x2"><td>1</td></tr>
<tr class="handicap"><td>2</td></tr>
<tr class="total"><td>3</td></tr>
</tbody>
<tbody>
<tr class="team"><td>10%</td></tr>
<tr class="1x2"><td>1</td></tr>
<tr class="handicap"><td>2</td></tr>
<tr class="total"><td>3</td></tr>
</tbody>
</table>
</body>
</html>
|
Огромное спасибо вам ребята!!!!! Очень помогли!:victory:
|
Как совместить код с фильтром
Ребята, прошу и молю:help: Нашел на просторах интернета код (я полностью поместил сюда его, чтоб не терялась работоспособность), который использует localStorage. Пытаюсь совместить с фильтром. Чтоб после перезагрузки не сбрасывались значения. Значения в input получается сохранить, а вот отфильтрованная таблица сбрасывается после перезагрузки страницы. Как это совместно реализовать?
<form id="ds_form">
<input name="first">
<input name="second">
<select name="third">
<option>Value1</option>
<option>Value2</option>
</select>
<div>
<input type="radio" id="contactChoice1" name="contact" value="email">
<label for="contactChoice1">Email</label>
<input type="radio" id="contactChoice2" name="contact" value="phone">
<label for="contactChoice2">Phone</label>
<input type="radio" id="contactChoice3" name="contact" value="mail">
<label for="contactChoice3">Mail</label>
</div>
<div>
<input type="checkbox" id="checkboxChoice1" name="checkbox1" value="email">
<label for="checkboxChoice1">Email</label>
<input type="checkbox" id="contactChoice2" name="checkbox2" value="phone">
<label for="checkboxChoice2">Phone</label>
<input type="checkbox" id="checkboxChoice3" name="checkbox3" value="mail">
<label for="checkboxChoice3">Mail</label>
</div>
</form>
<script>
let ds = document.forms[0];
ds.onchange = () => {
let json = JSON.stringify(Array.from(new FormData(ds)));
localStorage.setItem(ds.id, json);
};
document.addEventListener("DOMContentLoaded", () => {
let values = JSON.parse(localStorage.getItem(ds.id));
for (let i = 0; i < values.length; ++i) {
let el = ds[values[i][0]];
if (el.type === "checkbox")
el.setAttribute("checked", "");
else
el.value = values[i][1];
}
});
</script>
Еще есть код, который после перезагрузки страницы сохраняет значения input, но совместить с фильтром не получается? Опять же таблица возвращается к начальному виду.
<script>
(function(){
var input = document.getElementById('inp');
if (localStorage.inp) {
input.value = localStorage.inp; }
input.onchange = function() {
localStorage.inp = this.value; }
})();
</script>
Цитата:
|
| Часовой пояс GMT +3, время: 16:49. |