I want to show/hide tr when all td have same values in current tr.in second tr have 2 same value but i m able to hide/show . it will show hide when all td value same.
$('#contains').change( function() {
$('td:contains("text2")').parent().toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="contains" >contains text2
<br/>
<table border="1" style="text-align:center;">
<tr>
<th>Name</th><th>Lastname</th>
</tr>
<tr>
<td>text1</td><td>text2</td><td>text2</td>
</tr>
<tr>
<td>text3</td><td>text4</td><td>text4</td>
</tr>
</table>
with js (ES6):
const
chk_text2 = document.querySelector('#contains')
, tableRows = document.querySelectorAll('#my-table tbody tr')
;
chk_text2.onchange = () =>
{
tableRows.forEach( tr =>
{
tr.classList.toggle('noDisplay', !tr.innerText.includes('text2') && chk_text2.checked)
})
}
table {
border-collapse : collapse;
margin : 2em 1em;
font-family : Arial, Helvetica, sans-serif;
font-size : 14px;
}
td,th {
padding : .2em .8em;
border : 1px solid darkblue;
}
thead {
background : aquamarine;
}
.noDisplay {
display : none;
}
<input type="checkbox" id="contains" >contains text2
<br/>
<table id="my-table">
<thead>
<tr>
<th>Name</th><th>Lastname</th><th></th>
</tr>
</thead>
<tbody>
<tr>
<td>text2</td><td>text2</td><td>text2</td>
</tr>
<tr>
<td>text3</td><td>text4</td><td>text4</td>
</tr>
</tbody>
</table>
// handle click
document.querySelector('#contains').addEventListener('click', () => {
// filter items
const rowsToHide = Array.from(document.querySelectorAll('tr')).filter(row => {
// get first content
const content = row.querySelector('td').textContent
// check all items is equal to first element
return Array.from(row.querySelectorAll('td'))
.some(row => row.textContent !== content)
})
// perform action
rowsToHide.forEach(row => { row.style.display = 'none' })
})
Maybe something like this
$('#contains').
change( function()
{
$('tr').each(function()
{
var hiderow=1;
var firsttd = $('td',this)[0];
if(firsttd)
{
var firsttdtext =firsttd.innerHTML;
$('td',this).each(function(index,element)
{
if(index<1)
return;
if(firsttdtext != element.innerHTML)
hiderow=0;
});
if(hiderow==1)
$(this).toggle();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="contains" >Hide same values
<br/>
<table border="1" style="text-align:center;">
<tr>
<th>Name</th><th>Lastname</th>
</tr>
<tr>
<td>text2</td><td>text2</td><td>text2</td>
</tr>
<tr>
<td>text3</td><td>text4</td><td>text4</td>
</tr>
<tr>
<td>textxyz</td><td>textxyz</td><td>textxyz</td>
</tr>
</table>
Related
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')
I have the following codes. checkbox for compare value in table row
Problem:
1 ) when table value same multiple row it will hide all I want to complare 1 checkbox 1 row
2 ) why funtion will start work when checked box ? I want to start function onload window
Fiddle: http://jsfiddle.net/4sx1pdmn/
Can anyone advise with my codes?
function filterCondtn1(event) {
var element = event.target
var condt1 = document.getElementsByClassName("option")
for (var i = 0; i < condt1.length; i++) {
if (condt1[i].innerHTML.toLowerCase() == element.value.toLowerCase()) {
if (element.checked == true) {
condt1[i].parentElement.style = "display:none"
} else {
condt1[i].parentElement.style = "display:block"
}
}
}
}
table {
border-collapse : collapse;
margin : 2em 1em;
}
td,th {
padding : .2em .8em;
border : 1px solid darkblue;
}
<div id="InputOpts">
<input type="checkbox" value="1" oninput="filterCondtn1(event);">Option 1
<input type="checkbox" value="1" oninput="filterCondtn1(event);">Option 2
<input type="checkbox" value="2" oninput="filterCondtn1(event);">Option 3
</div>
<table id="myTable">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td class="option">1</td>
<td>1</td>
</tr>
<tr>
<td class="option">2</td>
<td>2</td>
</tr>
<tr>
<td class="option">3</td>
<td>3</td>
</tr>
<tr>
<td class="option">1</td>
<td>1</td>
</tr>
</table>
Sorry for my bad English, can't explain all what I need, hope you understand what I need
You should keep track of your selections with a Set. If you want multiple filters, you could use a Map instead. Add to the set if the option is enabled and remove if it gets disabled.
Use a class to hide the rows that do not meet the filter criteria.
const filterVals = new Set();
const isValid = (value) => filterVals.size === 0 || filterVals.has(value);
const handleInputChange = ({ target: { checked, value } }) => {
if (checked) filterVals.add(value);
else filterVals.delete(value);
updateTableRows();
}
const updateTableRows = () =>
document.querySelectorAll('.option').forEach(option => {
option.closest('tr').classList.toggle('hidden-row', !isValid(option.textContent));
});
document.querySelectorAll('#input-opts input[type="checkbox"]')
.forEach(input => input.addEventListener('input', handleInputChange));
table { border-collapse: collapse; }
table, th, td { border: thin solid grey; }
th, td { padding 0.25em; text-align: center; }
.hidden-row { display: none; }
#input-opts { margin-bottom: 1em; }
#input-opts label { margin-right: 1em; }
<div id="input-opts">
<label>Name 1 <input type="checkbox" value="1" /></label>
<label>Name 2 <input type="checkbox" value="2" /></label>
<label>Name 3 <input type="checkbox" value="3" /></label>
</div>
<table id="my-table">
<thead>
<tr><th>Name</th><th>Country</th></tr>
</thead>
<tbody>
<tr><td class="option">1</td><td>1</td></tr>
<tr><td class="option">2</td><td>2</td></tr>
<tr><td class="option">3</td><td>3</td></tr>
<tr><td class="option">1</td><td>1</td></tr>
</tbody>
</table>
a way to do that
const TD_option =
[...document.querySelectorAll('#myTable td.option')] // make an array
.map(el=>( // of objects { val, el }
{ val : el.textContent.trim().toLowerCase()
, tr : el.closest('tr')
}))
;
document
.querySelectorAll('#InputOpts input[type="checkbox"]')
.forEach( ckbx =>
{
ckbx.checked = true // all are displayed on document load
let chkVal = ckbx.value.toLowerCase()
ckbx.oninput = e =>
{
TD_option.forEach( row =>
{
if (chkVal == row.val )
row.tr.classList.toggle('noDisplay', !ckbx.checked )
})
}
})
table {
border-collapse : collapse;
margin : 2em 1em;
}
td,th {
padding : .2em .8em;
border : 1px solid darkblue;
}
.noDisplay {
display: none;
}
<div id="InputOpts">
<label><input type="checkbox" value="1">Option 1</label>
<label><input type="checkbox" value="2">Option 2</label>
<label><input type="checkbox" value="3">Option 3</label>
</div>
<table id="myTable">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td class="option">1</td>
<td>1</td>
</tr>
<tr>
<td class="option">2</td>
<td>2</td>
</tr>
<tr>
<td class="option">3</td>
<td>3</td>
</tr>
<tr>
<td class="option">1</td>
<td>1</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>
Have been dabbling around with this piece of code, only I could do with some input. Could really do with a follow up working examples altered code snippet if at all possible. Need to figure the filter/search - returning results being limited to a specified table heading ('th/tr' - tags), namely the Title heading and search within ONLY this area, though displaying the whole cells still (Title, Description and Date).Any questions I'll be pleased to help.
var input, table, rows, noMatches, markInstance;
$(document).ready(function init() {
input = document.getElementById('myInput');
noMatches = document.getElementById('noMatches');
table = document.getElementById('myTable');
rows = table.querySelectorAll('tr');
markInstance = new Mark(table);
input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
});
function ContactsearchFX() {
resetContent();
markInstance.unmark({
done: highlightMatches
});
}
function resetContent() {
$('.noMatchErrorText').remove();
//Remove this line to have a log of searches
//noMatches.textContent = '';
rows.forEach(function(row) {
$(row).removeClass('show');
});
}
function highlightMatches() {
markInstance.mark(input.value, {
each: showRow,
noMatch: onNoMatches,
})
}
function showRow(element) {
//alert(element);
$(element).parents('tr').addClass('show');
$(element).parents('tr').siblings('tr').addClass('show');
//Parents incase of several nestings
}
function onNoMatches(text) {
$('#myInput').after('<p class="noMatchErrorText">No records match: "' + text + '"</p>');
}
.input-wrap {
margin-bottom: 12px;
}
#myInput:invalid~.hints {
display: block;
}
#noMatches:empty,
#noMatches:empty+.hints {
display: none;
}
.style1 tr {
display: none;
}
.style1 .show {
display: table-row;
}
mark {
background: orange;
font-weight: bold;
color: black;
}
.style1 {
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"></script>
<div class="input-wrap">
<label>
Search Titles:
<input id="myInput" type="text" required
placeholder="Search Titles" />
</label>
</div>
<div class="hintsWrap">
<p id="noMatches"></p>
<p class="hints">
Hints: type "Title1", "Title2", "Title3"...
</p>
</div>
<br />
<br />
<table id="myTable" style="width: 100%" class="style1">
<tr>
<td>
<br />
<br />
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title1</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description1</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date1</td>
</tr>
</table>
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title2</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description2</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date2</td>
</tr>
</table>
<br />
<br />
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title3</td>
</tr>
<tr>
<th class="style1" style="height: 23px">Description</th>
<td style="height: 23px">description3</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date3</td>
</tr>
</table>
<br />
<br />
<table style="width: 100%">
<tr>
<td>
<table style="width: 100%">
<tr>
<th class="style1">Title</th>
<td>title4</td>
</tr>
<tr>
<th class="style1">Description</th>
<td>description4</td>
</tr>
<tr>
<th class="style1">Date</th>
<td>date4</td>
</tr>
</table>
</td>
</tr>
</table>
<br />
</td>
</tr>
</table>
As continuation from comments above, and since this was something basic that you would like to use, i posted it here.
I added some notes on the code but the essences are:
This is just a really basic approach without any use of libraries.
I play with classes in order to hide the table rows and also to mark the result
Although i leave the part on the script that display: none; the lines of the table, you can manipulate the CSS and delete it from the code.
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.querySelectorAll("tbody > tr");
for (i = 0; i < tr.length; i++) { // Loop through all table rows, and hide those who don't match the search query
td = tr[i].getElementsByTagName("td")[0]; // this will search on the Title col. You can change this to search on other cols.
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) { // found
tr[i].style.display = "";
tr[i].classList.add("mark"); // mark result
}
else { // didn't found
tr[i].style.display = "none";
tr[i].classList.remove("mark"); // unmark result
}
}
if (input.value === '') { // case the input is clear
tr[i].classList.remove("mark"); // unmark result
tr[i].style.display = "none";
}
}
}
table {position: relative; min-width: 320px;} /* */
tbody tr {opacity: 0;} /* this will hide the table's info + will show the result under the headers */
tr.mark {opacity: 1;} /* this will show the result row */
/* basic style (markers) to the result row - just for demonstration purpose */
tr.mark td {background: yellow;} /* (second) col */
tr.mark td:first-child {background: blue;} /* first col */
tr.mark td:last-child {background: orange;} /* third col*/
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search Titles..">
<table id="myTable">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>bla bla bla</td>
<td>description1</td>
<td>date1</td>
</tr>
<tr>
<td>yada yada yada</td>
<td>description2</td>
<td>date2</td>
</tr>
<tr>
<td>Another Title</td>
<td>description3</td>
<td>date3</td>
</tr>
</tbody>
</table>
Hope that it is what you searched for, and Enjoy code!
Solution 1. you can play with css selectors to achieve your goal:
#myTable table tr:first-child td mark {
background: orange;
font-weight: bold;
color: black;
}
mark {
background: initial;
}
Solution 2. edit your init function for sibling only titles like this:
$(document).ready(function init() {
input = document.getElementById('myInput');
noMatches = document.getElementById('noMatches');
/************************************************
NOTE :: your last table element doesn't match your template
************************************************/
table = document.querySelectorAll('#myTable table tr:first-child td');
rows = document.querySelectorAll('#myTable table tr');
markInstance = new Mark(table);
input.addEventListener('keyup', _.debounce(ContactsearchFX, 250));
});
Have fun
Only one row having class highlightRowSelected one time and that row's checkbox is ticked - this is working
How to make other checkboxes deselect which does not have class highlightRowSelected and also other rows checkbox es can be ticked but that should not add class highlightRowSelected to that row , only row click(not from checkbox col) should add the class highlightRowSelected to that row
you can change the function declaration and make a pure js call rather than specifying getdetails(row) in the html..
Also the rows are dynamic so cant hardcode id or something in html
Check out this fiddle: https://jsfiddle.net/y7jqb5hp/13/
function getdetails(row) {
el = window.event.srcElement;
if (el.id.substr(0, 7) == 'eachRow')
el = null;
if (row.cells[0].children[0].checked == false && el != null) {
row.cells[0].children[0].checked = true;
} else if (row.cells[0].children[0].checked == false && el != null) {
row.cells[0].children[0].checked = true;
}
$("#tableID tbody tr").each(function() {
$(this).removeClass("highlightRowSelected");
});
$(row).addClass("highlightRowSelected");
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
.highlightRowSelected {
background-color: #e2e2e2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableID">
<tr onclick="getdetails(this)">
<th>checkbox</th>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Alfreds </td>
<td>Maria </td>
<td>Germany</td>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Centro </td>
<td>Francisco </td>
<td>Mexico</td>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Ernst </td>
<td>Roland </td>
<td>Austria</td>
</table>
I just changed the second condition of your JS code, added to unselect others:
$('input:checkbox').removeAttr('checked');
And took away the call getdetails from the header row.
Also added:
$('input:checkbox').click(function(e) {
e.stopPropagation();
});
to handle the checkbox ticks separately from row clicks.
function getdetails(row) {
el = window.event.srcElement;
if (el.id.substr(0, 7) == 'eachRow')
el = null;
if (row.cells[0].children[0].checked == false && el != null) {
$('input:checkbox').removeAttr('checked');
row.cells[0].children[0].checked = true;
} else if (row.cells[0].children[0].checked == true && el != null) {
row.cells[0].children[0].checked = false;
}
$("#tableID tbody tr").each(function() {
$(this).removeClass("highlightRowSelected");
});
$(row).addClass("highlightRowSelected");
}
$('input:checkbox').click(function(e) {
e.stopPropagation();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
.highlightRowSelected {
background-color: #e2e2e2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableID">
<tr>
<th>checkbox</th>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Alfreds </td>
<td>Maria </td>
<td>Germany</td>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Centro </td>
<td>Francisco </td>
<td>Mexico</td>
</tr>
<tr onclick="getdetails(this)">
<td><input name="eachRow" type="checkbox" /> </td>
<td>Ernst </td>
<td>Roland </td>
<td>Austria</td>
</table>
update your js function:
function getdetails(row) {
if ($(row).find('input[type="checkbox"]').is(":checked")) {
$(row).find('input[type="checkbox"]').prop('checked', false);
$(row).removeClass("highlightRowSelected");
return false;
}
var isChecked = false;
$("#tableID tbody tr").each(function () {
if ($(this).find('input[type="checkbox"]').is(":checked")) {
isChecked = true;
}
});
if (isChecked) {
$(row).find('input[type="checkbox"]').prop('checked', true);
return false;
} else {
$('table input[type="checkbox"]').prop('checked', false);
$(row).find('input[type="checkbox"]').prop('checked', true);
}
$("#tableID tbody tr").each(function () {
$(this).removeClass("highlightRowSelected");
});
$(row).addClass("highlightRowSelected");
}
updated fiddle
use jquery to trigger the function,
ex.
<tr id="1" onclick="checkMe(this.id)"><input type='checkbox'></tr>
<tr id="2" onclick="checkMe(this.id)"><input type='checkbox'></tr>
jquery:
function checkMe(id){
$(this).closest('[type=checkbox]').attr('checked', true);
}