I'm trying to work a way where you can click a button and search by different columns in a table. I can figure out the buttons and to change the [0] to [1] to search different columns, but how would i make it more dynamic, using javascript. I only want to search by 1 column at a time, so only search by first name or only search by nationality etc...
it is a basic code, I did web programming 20 years ago and im trying to get back up to speed.
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (filter) {
if (txtValue.toUpperCase() == filter) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
} else {
tr[i].style.display = "";
}
}
}
}
<div class="w3-container">
<h2>All Information</h2>
<div class="w3-bar">
<button class="w3-button w3-black" style="width: 10%">#</button>
<button class="w3-button w3-teal" style="width: 10%">First Name</button>
<button class="w3-button w3-red" style="width: 10%">Last Name</button>
<button class="w3-button w3-yellow" style="width: 10%">Address</button>
<button class="w3-button w3-green" style="width: 10%">Age</button>
<button class="w3-button w3-blue" style="width: 10%">Date of Birth</button>
<button class="w3-button w3-purple" style="width: 10%">Nationality</button>
</div>
<input id="myInput" onkeyup="myFunction()" placeholder="Search by ID Number..." title="Type in a number" type="text">
<table id="myTable">
<tr class="header">
<th class="w3-center" style="width: 2%;">#</th>
<th style="text-align: left; width: 17%;">First Name</th>
<th style="text-align: left; width: 17%;">Last Name</th>
<th style="text-align: left; width: 16%;">Address</th>
<th style="text-align: left; width: 16%;">Age</th>
<th style="text-align: left; width: 16%;">Date of Birth</th>
<th style="text-align: left; width: 16%;">Nationality</th>
</tr>
<tr>
<td class="w3-center">1</td>
<td>John</td>
<td>Smith</td>
<td>Pearse Street</td>
<td>45</td>
<td>01/10/1977</td>
<td>English</td>
</tr>
<tr>
<td class="w3-center">11</td>
<td>Tim</td>
<td>Green</td>
<td>Rosedale Avenue</td>
<td>23</td>
<td>17/04/1999</td>
<td>American</td>
</tr>
<tr>
<td class="w3-center">114</td>
<td>Tom</td>
<td>Deane</td>
<td>Greenwood Road</td>
<td>42</td>
<td>27/11/1980</td>
<td>English</td>
</tr>
<tr>
<td class="w3-center">208</td>
<td>Anna</td>
<td>Green</td>
<td>Rosedale Avenue</td>
<td>23</td>
<td>11/06/1999</td>
<td>Scottish</td>
</tr>
<tr>
<td class="w3-center">259</td>
<td>Rachel</td>
<td>Waters</td>
<td>Station Road</td>
<td>87</td>
<td>11/02/1936</td>
<td>Irish</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>George</td>
<td>Taylor</td>
<td>Beach Avenue</td>
<td>52</td>
<td>30/07/1971</td>
<td>South African</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>Neil</td>
<td>Smyth</td>
<td>Beach Road</td>
<td>6</td>
<td>15/12/2016</td>
<td>Australian</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>Sarah</td>
<td>Smyth</td>
<td>Beach Road</td>
<td>30</td>
<td>06/01/1993</td>
<td>Australian</td>
</tr>
</table>
</div>
const column = 3
const searchFor = 'GRE'
for (const cell of document.querySelectorAll(`#myTable tr td:nth-child(${column})`))
if (cell.textContent.toUpperCase().includes(searchFor))
cell.style.background = 'lightgreen'
<table id="myTable">
<tr class="header">
<th class="w3-center" style="width: 2%;">#</th>
<th style="text-align: left; width: 17%;">First Name</th>
<th style="text-align: left; width: 17%;">Last Name</th>
<th style="text-align: left; width: 16%;">Address</th>
<th style="text-align: left; width: 16%;">Age</th>
<th style="text-align: left; width: 16%;">Date of Birth</th>
<th style="text-align: left; width: 16%;">Nationality</th>
</tr>
<tr>
<td class="w3-center">1</td>
<td>John</td>
<td>Smith</td>
<td>Pearse Street</td>
<td>45</td>
<td>01/10/1977</td>
<td>English</td>
</tr>
<tr>
<td class="w3-center">11</td>
<td>Tim</td>
<td>Green</td>
<td>Rosedale Avenue</td>
<td>23</td>
<td>17/04/1999</td>
<td>American</td>
</tr>
<tr>
<td class="w3-center">114</td>
<td>Tom</td>
<td>Deane</td>
<td>Greenwood Road</td>
<td>42</td>
<td>27/11/1980</td>
<td>English</td>
</tr>
<tr>
<td class="w3-center">208</td>
<td>Anna</td>
<td>Green</td>
<td>Rosedale Avenue</td>
<td>23</td>
<td>11/06/1999</td>
<td>Scottish</td>
</tr>
<tr>
<td class="w3-center">259</td>
<td>Rachel</td>
<td>Waters</td>
<td>Station Road</td>
<td>87</td>
<td>11/02/1936</td>
<td>Irish</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>George</td>
<td>Taylor</td>
<td>Beach Avenue</td>
<td>52</td>
<td>30/07/1971</td>
<td>South African</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>Neil</td>
<td>Smyth</td>
<td>Beach Road</td>
<td>6</td>
<td>15/12/2016</td>
<td>Australian</td>
</tr>
<tr>
<td class="w3-center">1</td>
<td>Sarah</td>
<td>Smyth</td>
<td>Beach Road</td>
<td>30</td>
<td>06/01/1993</td>
<td>Australian</td>
</tr>
</table>
Looking for something like that ? (first version)
const
btSearch = document.querySelector('#bt-search')
, txt2search = document.querySelector('#txt-2-search')
, searchResult = document.querySelector('#search-result')
, myTable = document.querySelector('#my-table')
;
btSearch.disabled = true
;
myTable.onclick = ({target:TH}) =>
{
if (!TH.matches('th')) return;
clearFounds();
btSearch.disabled = true;
if (TH.classList.toggle('selec'))
{
btSearch.disabled = false;
myTable.querySelectorAll('th.selec')
.forEach(th => th.classList.toggle('selec',th===TH))
}
}
btSearch.onclick=()=>
{
clearFounds();
let txt = txt2search.value.trim()
, Rtxt = new RegExp(txt, 'i')
, nCol = 1 + myTable.querySelector('th.selec').cellIndex
, counter = 0
;
if (txt==='')
{
searchResult.textContent = 'nothing to search...';
return;
}
myTable.querySelectorAll(`tr td:nth-child(${nCol})`).forEach(td =>
{
if(Rtxt.test(td.textContent))
{
counter++;
td.classList.add('found');
}
})
searchResult.textContent = (counter===0) ? 'no result' : `${counter} element(s) found`;
}
function clearFounds()
{
searchResult.textContent = '.';
myTable.querySelectorAll('td.found')
.forEach(td => td.classList.remove('found'));
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
margin : 1rem;
}
table {
border-collapse : separate;
border-spacing : 1px;
background-color : lightslategrey;
}
th { background: cadetblue; padding: .3em .6em; cursor: pointer; }
td { background: whitesmoke; padding: .2em .5em; }
tr *:first-child { text-align: center; font-style: oblique; }
tr * { white-space: nowrap; }
th:not(.selec):hover { background: orange; }
th.selec { background: orangered }
td.found { background: aquamarine; }
caption {
text-align : left;
padding : .4rem;
font-size : 1.2rem;
background-color: #a0dbdd;
}
#search-result {
float : right;
font-size : .9rem;
}
<table id="my-table">
<caption>
Find :
<input type="text" id="txt-2-search" placeholder="select a column first...">
<button id="bt-search"> do search </button>
<span id="search-result">0</span>
</caption>
<thead>
<tr>
<th>#</th><th>First Name</th><th>Last Name</th><th>Address</th><th>Age</th><th>Date of Birth</th><th>Nationality</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>John</td><td>Smith</td><td>Pearse Street</td><td>45</td><td>01/10/1977</td><td>English</td>
</tr>
<tr>
<td>11</td><td>Tim</td><td>Green</td><td>Rosedale Avenue</td><td>23</td><td>17/04/1999</td><td>American</td>
</tr>
<tr>
<td>114</td><td>Tom</td><td>Deane</td><td>Greenwood Road</td><td>42</td><td>27/11/1980</td><td>English</td>
</tr>
<tr>
<td>208</td><td>Anna</td><td>Green</td><td>Rosedale Avenue</td><td>23</td><td>11/06/1999</td><td>Scottish</td>
</tr>
<tr>
<td>259</td><td>Rachel</td><td>Waters</td><td>Station Road</td><td>87</td><td>11/02/1936</td><td>Irish</td>
</tr>
<tr>
<td>1</td><td>George</td><td>Taylor</td><td>Beach Avenue</td><td>52</td><td>30/07/1971</td><td>South African</td>
</tr>
<tr>
<td>1</td><td>Neil</td><td>Smyth</td><td>Beach Road</td><td>6</td><td>15/12/2016</td><td>Australian</td>
</tr>
<tr>
<td>1</td><td>Sarah</td><td>Smyth</td><td>Beach Road</td><td>30</td><td>06/01/1993</td><td>Australian</td>
</tr>
</tbody>
</table>
As the subject interested me...
And sorry, there may be a bit too many technical things here, but I've already spent a bit too many hours there, I'll come back to explain and comment. If any questions come up here in the meantime, I'll do my best to answer them.
const
txt2search = document.querySelector('#txt-2-search')
, searchResult = document.querySelector('#search-result')
, myTable = document.querySelector('#my-table')
, tableHeads = myTable.querySelectorAll('thead th')
, styleColHover = document.querySelector('#style-col-hover')
, mouseHoverTD = ({target: TD}) =>
{
let ref = (!!TD && TD.matches('td')) ? TD.cellIndex +1 : -1;
styleColHover.textContent = `td:nth-child(${ref}) { background: var(--col-hover);}`;
};
myTable.tBodies[0].onmouseenter = mouseHoverTD;
myTable.tBodies[0].onmousemove = mouseHoverTD;
myTable.tBodies[0].onmouseout =_=> mouseHoverTD({target:null});
txt2search.onkeyup = ({key}) =>
{
if (key==='Enter') searchProcess();
}
myTable.onclick = ({target:colElm}) =>
{
if (!colElm.matches('th, td')) return;
if (colElm.matches('td'))
{
tableHeads.forEach(th=>th.classList.remove('selec'));
tableHeads[colElm.cellIndex].classList.add('selec');
}
else if (colElm.classList.toggle('selec'))
{
tableHeads.forEach(th=>th.classList.toggle('selec', th===colElm));
}
searchProcess();
}
function clearSearch()
{
searchResult.textContent = '.';
myTable.querySelectorAll('td.found').forEach(td => td.classList.remove('found'));
}
function searchProcess()
{
let indxElm = myTable.querySelector('thead th.selec')?.cellIndex ?? 'x';
clearSearch();
if(isNaN(indxElm)) return;
let txt = txt2search.value.trim()
, Regtxt = new RegExp(txt, 'i')
, counter = 0
, query = 'tr td:nth-child('+ ++indxElm +')'
;
if (txt==='')
{
searchResult.textContent = 'nothing to search...';
return;
}
myTable.querySelectorAll(query).forEach(td =>
{
if(Regtxt.test(td.textContent))
{
counter++;
td.classList.add('found');
}
})
searchResult.textContent =
(counter===0) ? 'no result' : `${counter} element(s) found`;
}
:root {
--col-hover : #eeafdb;
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 16px;
margin : 1rem;
}
table {
border-collapse : separate;
border-spacing : 1px;
background-color : lightslategrey;
}
th { background: cadetblue; padding: .3em .6em; }
td { background: whitesmoke; padding: .2em .5em; }
tr *:first-child { text-align: center; font-style: oblique; }
tr * { white-space: nowrap; cursor: pointer; }
th:not(.selec):hover { background: orange; }
th.selec { background: orangered; }
td.found { background: aquamarine !important; }
caption {
text-align : left;
padding : .4rem;
font-size : 1.2rem;
background : #a0dbdd;
}
#search-result {
float : right;
font-size : .9rem;
}
<style id="style-col-hover"> td:nth-child(-1) { background : var(--col-hover);}</style>
<table id="my-table">
<caption>
Find :
<input type="text" id="txt-2-search" placeholder="select a column first...">
<span id="search-result">0</span>
</caption>
<thead>
<tr>
<th>#</th><th>First Name</th><th>Last Name</th><th>Address</th><th>Age</th><th>Date of Birth</th><th>Nationality</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>John</td><td>Smith</td><td>Pearse Street</td><td>45</td><td>01/10/1977</td><td>English</td>
</tr>
<tr>
<td>11</td><td>Tim</td><td>Green</td><td>Rosedale Avenue</td><td>23</td><td>17/04/1999</td><td>American</td>
</tr>
<tr>
<td>114</td><td>Tom</td><td>Deane</td><td>Greenwood Road</td><td>42</td><td>27/11/1980</td><td>English</td>
</tr>
<tr>
<td>208</td><td>Anna</td><td>Green</td><td>Rosedale Avenue</td><td>23</td><td>11/06/1999</td><td>Scottish</td>
</tr>
<tr>
<td>259</td><td>Rachel</td><td>Waters</td><td>Station Road</td><td>87</td><td>11/02/1936</td><td>Irish</td>
</tr>
<tr>
<td>1</td><td>George</td><td>Taylor</td><td>Beach Avenue</td><td>52</td><td>30/07/1971</td><td>South African</td>
</tr>
<tr>
<td>1</td><td>Neil</td><td>Smyth</td><td>Beach Road</td><td>6</td><td>15/12/2016</td><td>Australian</td>
</tr>
<tr>
<td>1</td><td>Sarah</td><td>Smyth</td><td>Beach Road</td><td>30</td><td>06/01/1993</td><td>Australian</td>
</tr>
</tbody>
</table>
Here's my take Dar.
//Define a column to look in
// const column = 4
//Get the value from the input
// const searchFor = document.getElementById('myInput').value
//Grab all the cells for the column
columnCells = Array.from(document.querySelectorAll(`#myTable tr td:nth-child(${column})`))
//Clear out previous matches
columnCells.forEach(cell=>cell.style.background = 'white')
//Filter the cells by the searchFor term
matchingCells = columnCells.filter(cell=>{
return cell.textContent.toLowerCase().includes(searchFor.toLowerCase()) && searchFor != ""
})
//Color them
matchingCells.forEach(cell=>cell.style.background = 'yellow')
Related
What I am trying to achieve:
I currently got two working buttons with a static value which is Yes.
<button type="button" id="foo_btn" value="Yes" class="btn">Foo</button>
<button type="button" id="bar_btn" value="Yes" class="btn">Bar</button>
When clicked it will filter a table based on the column's value and only show the rows which has the value Yes in that specific column in them.
Currently I use an switch statement to check the id of the button clicked and then set a variable which determines what column to be filtered, but I don't like this approach as if I include several columns/buttons, it will get rather long and messy. Also I don't like working with switch statements.
I also tested the performance of each event in Developer Tools in the Perfomance section and noticed that each task takes over a second to perform. Is there any superior solution to this rather than using switch statements?
Working example of what I've tried but with an ugly approach:
$('#foo_btn, #bar_btn').on('click', function() {
var val = $(this).val().toLowerCase();
switch(this.id) {
case 'foo_btn':
col = 'td:nth-child(1)';
break;
case 'bar_btn':
col = 'td:nth-child(2)';
break;
}
$(col).filter(function() {
$('tr:not(:has(th))').show();
return $(this).text().toLowerCase().indexOf(val);
}).parent().hide();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="foo_btn" value="Yes" class="btn">Foo</button>
<button type="button" id="bar_btn" value="Yes" class="btn">Bar</button>
<table class="table">
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Yes</td>
<td>Yes</td>
</tr>
</table>
Comment
I feel like this is a really simple solution to a simple problem which I've just gotten my brain tangled in. I appreciate all help I can get.
Based on the working example in your question you could make use of the html data property and bake the desired column right into the button itself.
e.g.
<button type="button" id="foo_btn" value="Yes" data-column="1" class="btn">Foo</button>
and inside the click event listener's callback function you can get the value of data-colum using
col = 'td:nth-child(' + $(this).data('column') + ')';
Here's the complete example:
$('#foo_btn, #bar_btn').on('click', function() {
var val = $(this).val().toLowerCase();
col = 'td:nth-child(' + $(this).data('column') + ')';
$(col).filter(function() {
$('tr:not(:has(th))').show();
return $(this).text().toLowerCase().indexOf(val);
}).parent().hide();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="foo_btn" value="Yes" data-column="1" class="btn">Foo</button>
<button type="button" id="bar_btn" value="Yes" data-column="2" class="btn">Bar</button>
<table class="table">
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>No</td>
<td>No</td>
</tr>
<tr>
<td>Yes</td>
<td>Yes</td>
</tr>
</table>
may be this solution would fit for you?
function getColumnIndex(colName) {
var headerCell = $('.table tr:first-child() > th:contains(' + colName + ')')
return headerCell.length ? (headerCell.index() + 1) : -1
}
function showOnlyValues(columnName, valueToShow) {
var colIndex = getColumnIndex(columnName)
$('td:nth-child(' + colIndex + ')').filter(function() {
$('tr:not(:has(th))').show();
return $(this).text().toLowerCase().indexOf(valueToShow);
}).parent().hide();
}
$('.filterBtn').on('click', function() {
var clickedBtn = $(this);
showOnlyValues(clickedBtn.data('columnName'), clickedBtn.val().toLowerCase());
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" value="Yes" class="btn filterBtn" data-column-name="Foo">Foo</button>
<button type="button" value="Yes" class="btn filterBtn" data-column-name="Bar">Bar</button>
<table class="table">
<tr>
<th>Foo</th>
<th>Bar</th>
</tr>
<tr>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Yes</td>
<td>No</td>
</tr>
</table>
I am using bootstrap filter for searching. But,for example when I type 'n' it shows all the name having 'n' like nathan, arjan . I don't want that.I want like this : if i type 'n' it will show only the names which starts with 'n' like nathaan,narima.
my blade.php code here:
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<tbody id="myTable">
<tr>
<td>John</td>
</tr>
<tr>
<td>Anja</td>
</tr>
</tbody>
my script part here
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
There is a method called startsWith that you can use. The documentation can be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
<script>
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().startsWith(value))
});
});
});
</script>
you can change the method if you want.
$("#myInput").bind("keyup", function() {
var text = $(this).val().toLowerCase();
var items = $("tr td");
//first, hide all:
items.parent().hide();
//show only those matching user input:
items.filter(function () {
return $(this).text().toLowerCase().indexOf(text) == 0;
}).parent().show();
});
Another way would be using RegExp:
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
/* $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) */
const searchRegEx = new RegExp(`^${value}`, 'i');
$(this).toggle(searchRegEx.test($(this).text().trim()));
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<table class="table table-bordered">
<tbody id="myTable">
<tr>
<td>John</td>
</tr>
<tr>
<td>Anja</td>
</tr>
</tbody>
</table>
Using .charAt(0) for result set to be filtered with first character match
Basic example from w3schools modified
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
#myInput {
background-image: url('/css/searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myTable {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
font-size: 18px;
}
#myTable th, #myTable td {
text-align: left;
padding: 12px;
}
#myTable tr {
border-bottom: 1px solid #ddd;
}
#myTable tr.header, #myTable tr:hover {
background-color: #f1f1f1;
}
</style>
</head>
<body>
<h2>My Customers</h2>
<input type="text" id="myInput" onkeyup="filterBy()" placeholder="Search..." title="Type in a name">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>Marimba</td>
<td>Something</td>
</tr>
<tr>
<td>Marimba</td>
<td>Something</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
</table>
<script>
function filterBy() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
if (txtValue.toUpperCase().charAt(0) == filter.charAt(0)) {
tr[i].style.display = "";
}
} else {
tr[i].style.display = "none";
}
if(filter.length == 0)
{
tr[i].style.display = "";
}
}
}
}
</script>
</body>
</html>
I'm trying to add an individual search box for each table column without success.
What should be added to code below in order to make it work?
Currently my code contains a single search box for first column only.
Please run snippet to get full details.
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
p.a {
white-space: nowrap;
}
h2 {
text-align: center;
font-family: Helvetica, Arial, sans-serif;
}
table {
margin-left: auto;
margin-right: auto;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
font-family: Helvetica, Arial, sans-serif;
font-size: 90%;
white-space:nowrap;
}
table tbody tr:hover {
background-color: #dddddd;
}
.wide {
width: 90%;
}
<h2> Title here </h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name"><table border="1" class="dataframe wide" id="myTable">
<thead>
<tr style="text-align: right;">
<th></th>
<th>KEY</th>
<th>DEVREVSTEP</th>
<th>WW32</th>
<th>WW33</th>
<th>WW34</th>
<th>WW35</th>
<th>WW36</th>
<th>WW37</th>
<th>WW38</th>
<th>WW39</th>
<th>WW40</th>
<th>Rule</th>
<th>LINK</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>First</td>
<td>A</td>
<td>-0.64</td>
<td>6.47</td>
<td>23.14</td>
<td>3.51</td>
<td>0.13</td>
<td>-0.41</td>
<td>-0.59</td>
<td>-0.31</td>
<td>33.13</td>
<td>A</td>
<td>Google.com</td>
</tr>
<tr>
<th>1</th>
<td>Second</td>
<td>B</td>
<td>-18.04</td>
<td>-18.42</td>
<td>-17.44</td>
<td>-16.35</td>
<td>-19.06</td>
<td>-17.49</td>
<td>-18.62</td>
<td>-17.92</td>
<td>-18.23</td>
<td>C</td>
<td>Amazon.com</td>
</tr>
<tr>
<th>2</th>
<td>Third</td>
<td>C</td>
<td>NaN</td>
<td>NaN</td>
<td>-0.59</td>
<td>2.25</td>
<td>-0.33</td>
<td>0.55</td>
<td>-0.53</td>
<td>8.96</td>
<td>17.53</td>
<td>B</td>
<td>Ebay.com</td>
</tr>
<tr>
<th>3</th>
<td>Fourth</td>
<td>A</td>
<td>-0.18</td>
<td>3.25</td>
<td>7.63</td>
<td>1.90</td>
<td>-0.19</td>
<td>0.41</td>
<td>0.15</td>
<td>0.20</td>
<td>17.31</td>
<td>A</td>
<td>Yahoo.com</td>
</tr>
<tr>
<th>4</th>
<td>Fourth</td>
<td>A</td>
<td>0.24</td>
<td>-3.25</td>
<td>-6.42</td>
<td>-1.51</td>
<td>0.60</td>
<td>-0.01</td>
<td>0.25</td>
<td>-0.02</td>
<td>-15.13</td>
<td>A</td>
<td>MSN.com</td>
</tr>
<tr>
<th>5</th>
<td>First</td>
<td>D</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>5.06</td>
<td>NaN</td>
<td>1.27</td>
<td>-0.56</td>
<td>13.24</td>
<td>A</td>
<td>Google.com</td>
</tr>
</tbody>
</table>
If you want to show only rows that are a match for all entered filter values - then you best loop over all the input fields on each change, that is easiest to handle.
I inserted input fields into the table header cells here, and then simply select them using getElementsByTagName - you can change that to a different position and / or using a different method to select them (f.e. by class maybe), it might need some slight adaptations then.
Notice how in both loops I start with the index 1 here, not 0 - to ignore the first table row in the i loop (because the header row should not disappear; could be done differently by selecting only the rows in the tbody to begin with), and to ignore the first cell in the j loop. And since the number of input fields is one less than the number of cells per row, I access the input using index j - 1, got get the one corresponding to the cell index.
This probably leaves room for refinements in several places, but should be enough to illustrate the basic principle.
function myFunction() {
var inputs, table, tr, i, j, inputValue, txtValue, showRow;
inputs = document.getElementsByTagName("input");
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
showRow = true;
for (j = 1; j < tr[i].cells.length; j++) {
inputValue = inputs[j - 1].value
txtValue = tr[i].cells[j].textContent || tr[i].cells[j].innerText;
if (inputValue != "" && txtValue.toUpperCase().indexOf(inputValue.toUpperCase()) == -1) {
showRow = false;
break;
}
}
tr[i].style.display = showRow ? "" : "none";
}
}
p.a {
white-space: nowrap;
}
h2 {
text-align: center;
font-family: Helvetica, Arial, sans-serif;
}
table {
margin-left: auto;
margin-right: auto;
}
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
text-align: left;
font-family: Helvetica, Arial, sans-serif;
font-size: 90%;
white-space: nowrap;
}
table tbody tr:hover {
background-color: #dddddd;
}
.wide {
width: 90%;
}
<h2> Title here </h2>
<table border="1" class="dataframe wide" id="myTable">
<thead>
<tr style="text-align: right;">
<th></th>
<th><input type="text" onkeyup="myFunction()"><br>KEY</th>
<th><input type="text" onkeyup="myFunction()"><br>DEVREVSTEP</th>
<th><input type="text" onkeyup="myFunction()"><br>WW32</th>
<th><input type="text" onkeyup="myFunction()"><br>WW33</th>
<th><input type="text" onkeyup="myFunction()"><br>WW34</th>
<th><input type="text" onkeyup="myFunction()"><br>WW35</th>
<th><input type="text" onkeyup="myFunction()"><br>WW36</th>
<th><input type="text" onkeyup="myFunction()"><br>WW37</th>
<th><input type="text" onkeyup="myFunction()"><br>WW38</th>
<th><input type="text" onkeyup="myFunction()"><br>WW39</th>
<th><input type="text" onkeyup="myFunction()"><br>WW40</th>
<th><input type="text" onkeyup="myFunction()"><br>Rule</th>
<th><input type="text" onkeyup="myFunction()"><br>LINK</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>First</td>
<td>A</td>
<td>-0.64</td>
<td>6.47</td>
<td>23.14</td>
<td>3.51</td>
<td>0.13</td>
<td>-0.41</td>
<td>-0.59</td>
<td>-0.31</td>
<td>33.13</td>
<td>A</td>
<td>Google.com</td>
</tr>
<tr>
<th>1</th>
<td>Second</td>
<td>B</td>
<td>-18.04</td>
<td>-18.42</td>
<td>-17.44</td>
<td>-16.35</td>
<td>-19.06</td>
<td>-17.49</td>
<td>-18.62</td>
<td>-17.92</td>
<td>-18.23</td>
<td>C</td>
<td>Amazon.com</td>
</tr>
<tr>
<th>2</th>
<td>Third</td>
<td>C</td>
<td>NaN</td>
<td>NaN</td>
<td>-0.59</td>
<td>2.25</td>
<td>-0.33</td>
<td>0.55</td>
<td>-0.53</td>
<td>8.96</td>
<td>17.53</td>
<td>B</td>
<td>Ebay.com</td>
</tr>
<tr>
<th>3</th>
<td>Fourth</td>
<td>A</td>
<td>-0.18</td>
<td>3.25</td>
<td>7.63</td>
<td>1.90</td>
<td>-0.19</td>
<td>0.41</td>
<td>0.15</td>
<td>0.20</td>
<td>17.31</td>
<td>A</td>
<td>Yahoo.com</td>
</tr>
<tr>
<th>4</th>
<td>Fourth</td>
<td>A</td>
<td>0.24</td>
<td>-3.25</td>
<td>-6.42</td>
<td>-1.51</td>
<td>0.60</td>
<td>-0.01</td>
<td>0.25</td>
<td>-0.02</td>
<td>-15.13</td>
<td>A</td>
<td>MSN.com</td>
</tr>
<tr>
<th>5</th>
<td>First</td>
<td>D</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>NaN</td>
<td>5.06</td>
<td>NaN</td>
<td>1.27</td>
<td>-0.56</td>
<td>13.24</td>
<td>A</td>
<td>Google.com</td>
</tr>
</tbody>
</table>
I developed clicking on the parent node to display its child row. I just need to enable to click on the child data should open its sub child rows as recursive one or table tree. Could anyone add your logic which will help me to understand and help the same to others?
document.getElementById("products").addEventListener("click", function(e) {
if (e.target.tagName === "A") {
e.preventDefault();
var row = e.target.parentNode.parentNode;
while ((row = nextTr(row)) && !/\bparent\b/ .test(row.className))
toggle_it(row);
}
});
function nextTr(row) {
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
function toggle_it(item){
if (/\bopen\b/.test(item.className))
item.className = item.className.replace(/\bopen\b/," ");
else
item.className += " open";
}
tbody tr {
display : none;
}
tr.parent {
display : table-row;
}
tr.open {
display : table-row;
}
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class="container">
<table class="table" id="products">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Destination</th>
<th>Updated on</th>
</tr>
</thead>
<tbody>
<tr class="parent">
<td>+Oranges</td>
<td>100</td>
<td>On Store</td>
<td>22/10</td>
</tr>
<tr>
<td>121</td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr>
<td>212</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr>
<td>212</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr class="parent">
<td>+Apples</td>
<td>100</td>
<td>On Store</td>
<td>22/10</td>
</tr>
<tr>
<td>120</td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr>
<td>120</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
</tbody>
</table>
</div>
Updated answer
I've changed almost everything and simplified the code:
The toggle buttons are added automatically,
+ changes to - when the parent is opened,
The table, the classes for opened and visible elements, and the buttons are passed as parameters,
It could be used on multiple table,
…
I've created a repository with that code on GitHub:
https://github.com/TakitIsy/table-to-tree
/* ---- < MAIN FUNCTION > ---- */
function tableToTree(table_Selector, tr_OpenedClass, tr_VisibleClass, tr_ToggleButton) {
// Table elements variables
var table = document.querySelector(table_Selector);
var trs = document.querySelectorAll(table_Selector + " tr");
// Add the buttons above the table
var buttons = document.createElement('div');
buttons.innerHTML = '<button>[‒] All</button><button>[+] All</button>';
table.insertBefore(buttons, table.childNodes[0]);
buttons = buttons.querySelectorAll('button');
// Add the actions of these buttons
buttons[0].addEventListener("click", function() {
trs.forEach(function(elm) {
elm.classList.remove(tr_OpenedClass);
elm.classList.remove(tr_VisibleClass);
});
});
buttons[1].addEventListener("click", function() {
trs.forEach(function(elm) {
if (elm.innerHTML.includes(tr_ToggleButton))
elm.classList.add(tr_OpenedClass);
elm.classList.add(tr_VisibleClass);
});
});
// Next tr function
function nextTr(row) {
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
// On creation, automatically add toggle buttons if the tr has childs elements
trs.forEach(function(tr, index) {
if (index < trs.length - 1) {
if (+tr.getAttribute("level") < +trs[index + 1].getAttribute("level")) {
var elm1 = tr.firstElementChild;
elm1.innerHTML = tr_ToggleButton + elm1.innerHTML;
}
}
});
// Use the buttons added by the function above
table.addEventListener("click", function(e) {
// Event management
if (!e) return;
if (e.target.outerHTML !== tr_ToggleButton) return;
e.preventDefault();
// Get the parent tr and its level
var row = e.target.closest("tr");
row.classList.toggle(tr_OpenedClass);
var lvl = +(row.getAttribute("level"));
// Loop to make childs visible/hidden
while ((row = nextTr(row)) && ((+(row.getAttribute("level")) == (lvl + 1)) || row.className.includes(tr_VisibleClass))) {
row.classList.remove(tr_OpenedClass);
row.classList.toggle(tr_VisibleClass);
}
});
}
/* ---- </ MAIN FUNCTION > ---- */
// Call the above main function to make the table tree-like
tableToTree('#myTable', 'opened', 'visible', '<span class="toggle"></span>');
tbody tr {
display: none;
}
tr[level="0"],
tr.visible {
display: table-row;
}
td {
background: #ccc;
padding: 4px 8px 4px 32px;
text-align: left;
}
tr[level="1"] td {
background: #ddd;
padding-left: 40px;
}
tr[level="2"] td {
background: #eee;
padding-left: 48px;
}
tr .toggle {
position: absolute;
left: 16px;
cursor: pointer;
}
.toggle::after {
content: "[+]";
}
.opened .toggle::after {
content: "[‒]";
}
<table id="myTable">
<tbody>
<tr level="0">
<td>Parent 1</td>
</tr>
<tr level="1">
<td>Match 1</td>
</tr>
<tr level="1">
<td>Match 2</td>
</tr>
<tr level="0">
<td>Parent 2</td>
</tr>
<tr level="1">
<td>Mismatch 1</td>
</tr>
<tr level="1">
<td>Mismatch 2</td>
</tr>
<tr level="2">
<td>Mismatch 2.1</td>
</tr>
</tbody>
</table>
<br>
⋅
⋅
⋅
Old answer
I played a little with your code…
Trying to use as many as possible of existing functions/methods to make the code cleaner and easier to read and understand.
… and ended-up with that snippet:
(See comments in my code for more details)
document.getElementById("products").addEventListener("click", function(e) {
// I think using the not equal is nicer here, just my opinion… Less indenting.
if (!e) return; // Exit if null
if (e.target.tagName !== "A") return; // Exit if not A element
e.preventDefault();
var row = e.target.closest("tr"); // Better than parent parent!
var cls = row.classList[0]; // Get the first class name (the only one in our html)
var lvl = +(cls.slice(-1)) + 1; // Unary operator +1 on the last character
cls = cls.slice(0, -1) + lvl; // Replace the last char with lvl to get the class to be toggled
// Check if the row is of the class to be displayed OR if the row is already opened
// (so that clicking close on parent also closes sub-childs)
while ((row = nextTr(row)) && (row.className.includes(cls) || row.className.includes("open")))
row.classList.toggle("open"); // Better than the function you created, it already exists!
});
function nextTr(row) {
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
// Select all the tr childs elements (all levels except 0
var allChilds = document.querySelectorAll("tr[class^=level]:not(.level0)");
// Added the below for buttons after comments
document.getElementById("openAll").addEventListener("click", function() {
allChilds.forEach(function(elm){
elm.classList.add("open");
});
});
document.getElementById("closeAll").addEventListener("click", function() {
allChilds.forEach(function(elm){
elm.classList.remove("open");
});
});
tbody tr {
display: none;
}
/* Simplified */
tr.level0,
tr.open {
display: table-row;
}
/* Added colors for better visibility */
tr.level0 {
background: #ccc;
}
tr.level1 {
background: #ddd;
}
tr.level2 {
background: #eee;
}
/* Added some more styling after comment */
tr td {
padding: 0.2em 0.4em;
}
tr td:first-of-type {
position: relative;
padding: 0.2em 1em;
}
tr td a {
color: inherit;
/* No special color */
text-decoration: inherit;
/* No underline */
position: absolute;
left: 0.25em;
}
tr.level1 td:first-of-type {
padding-left: 1.5em;
}
tr.level2 td:first-of-type {
padding-left: 2em;
}
<button id="openAll">+ All</button>
<button id="closeAll">- All</button>
<table class="table" id="products">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Destination</th>
<th>Updated on</th>
</tr>
</thead>
<tbody>
<tr class="level0">
<td>+Oranges</td>
<td>100</td>
<td>On Store</td>
<td>22/10</td>
</tr>
<tr class="level1">
<td>121</td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr class="level1">
<td>+212</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr class="level2">
<td>212</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr class="level2">
<td>212</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr class="level0">
<td>+Apples</td>
<td>100</td>
<td>On Store</td>
<td>22/10</td>
</tr>
<tr class="level1">
<td>120</td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr class="level1">
<td>+120</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
<tr class="level2">
<td>120</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr class="level2">
<td>120</td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
</tbody>
</table>
I hope it helps!
I have three tables and i want to check wheter they contain a specific element, e.g. a button with the value 'Previous'. I solved it by using the jquery function find and writing a function, but i need to solve this problem without jquery. Is this possible?
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = $(element).find("input[type=button]");
for (i=0; i<=check.length-1; i++) {
if (check[i].getAttribute("value") == "Previous") {
has_prev_button = true;
}
}
if (has_prev_button) {
document.write("<p>The selected table has a Previous button</p>");
} else {
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Use element.querySelectorAll:
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = element.querySelectorAll("input[type=button]");
for (i=0; i<=check.length-1; i++)
{
if (check[i].value == "Previous")
{
has_prev_button = true;
}
}
if (has_prev_button)
{
document.write("<p>The selected table has a Previous button</p>");
}
else
{
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Simply use document.querySelectorAll along with the classes spaced apart.
For example, if I want to find the button in the 3rd section and change its background color:
jQuery
$('.my_sections').eq(2).find('.my_button').css('background', 'pink')
Vanilla JS
document.querySelectorAll('.my_sections .my_button')[2].style.background = 'pink'
Similarly, If I wanted to check how many buttons I had of the my_button class:
document.querySelectorAll('.my_sections .my_button').length