Showing and Hiding Table Rows Based Off Alphabet Buttons - javascript

I have a table with a lot of rows in it, and I want to give users the ability to click an 'A' button and all the results that start with 'A' are displayed. They could do the same for every letter. This is what I've come up with so far:
HTML
<input type="button" id="aSort" value="A" onclick="alphaSort(this.value);">
<table>
<thead>
<tr>
<td>Title</td>
<td>Description</td>
<td>Active</td>
</tr>
</thead>
<tbody>
<tr>
<td name="title">Apple</td>
<td>It's a fruit</td>
<td>Active</td>
</tr>
<tr>
<td name="title">Pear</td>
<td>It's also fruit</td>
<td>No</td>
</tr>
</tbody>
</table>
JS
function alphaSort(val) {
//pseudocode
var $rows = $('td[name=title]');
$rows.forEach(function(e) {
if(e.innerText == val + '%') {
e.closest('tr').show();
} else {
e.closest('tr').hide();
}
}
}
So with what I have here, the idea is if the user clicked the button only the Apple row would show. Ideally the function would be case insensitive. Could someone help me with how to properly iterate through all the table rows efficiently and compare the value stored in the title row?

you can use startsWith function : https://www.w3schools.com/jsref/jsref_startswith.asp
like this :
$("#aSort").click(function(){
var $rows = $('td[name=title]');
var val = $(this).val()
$rows.each(function() {
if($(this).text().startsWith(val)) {
$(this).closest('tr').show();
} else {
$(this).closest('tr').hide();
}
})
})
https://jsfiddle.net/xpvt214o/899140/

Related

jquery - show / hide elements rows by elemenst in data-id array

I have table with rows like that:
<tr class="listRow" data-id="[11,0]">...</tr>
<tr class="listRow" data-id="[1,2,3]">...</tr>
How i can using JQuery filter specific rows with element in array? For example by button click show all rows with 1 in array and hide rest.
Edit - my sample code so far:
i don't know how to filtering elements in data-id array.
$(document).on('click','#filterList',function()
{
var element = $(this).data("id");
// how to filter elements in rows
}
);
If i understand correctly:
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
$('#check').click(function() {
$('.listRow').each(function() {
if($.inArray(1, $(this).data().id)>-1) {
$(this).show();
}
else {
$(this).hide()
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
<thead>
<tr class="listRow" data-id="[1,0]">
<th class="tg-0pky">Here is 1</th>
<th class="tg-0pky">xxxx</th>
<th class="tg-0pky"></th>
<th class="tg-0pky"></th>
</tr>
</thead>
<tbody>
<tr class="listRow" data-id="[11,0]">
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[15,0]" >
<td class="tg-0pky">Not 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
<tr class="listRow" data-id="[1,0,3]">
<td class="tg-0pky" >Here is 1</td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
<td class="tg-0pky"></td>
</tr>
</tbody>
</table>
<button id="check">
Click
</button>
when you press the button, loop through all the elements that have a data-id
parse the data-id as json, which will give you an array
if the array includes the id you're looking for, set the class to hide or show (where they have the display css assigned accordingly)
here's what that might look like without jquery and using style and opacity. Usually it's done using class but this is for demonstration purposes, changing to use classes should be straight forward.
function findElsById(id){
var matches = []
document.querySelectorAll('[data-id]').forEach(function(el){
try{
var arr = JSON.parse(el.dataset.id)
if (arr.includes(id)) matches.push(el)
} catch (e){
// prolly not valid json
}
})
return matches
}
function show(id){
var els = findElsById(id);
console.log('show', id, '\nshowing: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:1'
})
}
}
function hide(id){
var els = findElsById(id);
console.log('hide', id, '\nhiding: ', els)
if (els) {
els.forEach(function(el){
el.style = 'opacity:0.1'
})
}
}
<table>
<tr class="listRow" data-id="[1,0]"><td>1, 0</td></tr>
<tr class="listRow" data-id="[1,2]"><td>1, 2</td></tr>
</table>
<button onclick="hide(0)">-0</button>
<button onclick="hide(1)">-1</button>
<button onclick="hide(2)">-2</button>
<button onclick="show(0)">+0</button>
<button onclick="show(1)">+1</button>
<button onclick="show(2)">+2</button>

Live search in table for specific column

I'm currently trying to create a live search for a specific column in a table. I've searched a bit but I can only find solutions to search over all columns. This is my code:
function searchInTable(table) {
var value = this.value.toLowerCase().trim();
jQuery(table).each(function (index) {
if (!index) return;
jQuery(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search-table-input" class="search-table-input" type="text"
onkeyup="searchInTable('.table tr')" placeholder="Search Number...">
<table class="table">
<thead>
<tr>
<th class="table-number">
<span class="nobr">Number</span>
</th>
<th class="table-date">
<span class="nobr">Date</span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a>264</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>967</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>385</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
<tr>
<td>
<a>642</a>
</td>
<td>
<span>2019-01-02</span>
</td>
</tr>
</tbody>
</table>
My function has some errors and don't work like it should.
How can I change my function that way that when I start typing only the number gets filtered? I need to make the function dynamically so that I can pass the column which should be used for the search.
The line that's causing it to search over all the columns is this one:
jQuery(this).find("td").each(function () {
...which takes each cell in the current row and looks to see if it contains value. If you only want to check as specific column, you should pass in the column index as something like columnIndex, and then you can select the correct column by doing jQuery(this).find("td").eq(columnIndex), using jQuery's .eq() function to select the correct one. The code should look something like this:
function searchInTableColumn(table, columnIndex) {
//check this.value exists to avoid errors
var value = this.value ? this.value.toLowerCase().trim() : "";
jQuery(table).each(function (index) {
if (!index) return;
var tableCell = jQuery(this).find("td").eq(columnIndex);
var id = tableCell.text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
});
}
Then you can call searchInTableColumn(table, 0) and it will only look in the first column.

Get clicked column index from row click

I have a row click event. Recently had to add a checkbox to each row. How can I identify the clicked cell on row click event?
Or prevent row click when clicked on the checkbox.
Attempts: this.parentNode.cellIndex is undefined on the row click event.
function pop(row){
alert(row.cells[1].innerText);
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Do you want something like this? You can just check the type attribute of the source element of the event and validate whether to allow it or not, you can stop the event using e.stopPropagation();return;.
function pop(e, row) {
console.log(e.srcElement.type);
if(e.srcElement.type === 'checkbox'){
e.stopPropagation();
return;
}else{
console.log(row);
alert(row.cells[1].innerText);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event, this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
You should pass in the event details to your function and check the target property:
function pop(e){
// If the target is not a checkbox...
if(!e.target.matches("input[type='checkbox']")) {
alert(e.target.cellIndex);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event)">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Note: If you have nested elements inside the <td>, you might want to check e.target.closest("td") instead.
Note 2: You might need a polyfill for the matches method depending on which browsers you're supporting.
Here is an example if you don't want to attach a listener on every row :
document.getElementById("majorCities").addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var tr = e.target.parentElement.parentElement;
var city = tr.cells[1].innerHTML;
console.log(city+":checked="+checked);
}
});
<table id="majorCities" style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>London</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Paris</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>New-York</td>
</tr>
</table>
window.pop = function(row){
console.log('here');
var parent = row.parentNode;
Array.from(row.parentNode.querySelectorAll('tr')).forEach(function(tr, index){
if (tr === row) {
alert(index)
}
})
}
https://jsfiddle.net/sz42oyvm/
Here is for the pleasure, another example with an object containing the cities' names and a method to draw the table with ids corresponding to the name of the clicked city, so getting the clicked name is easier.
(function () {
var mySpace = window || {};
mySpace.cities = {};
mySpace.cities.pointer = document.getElementById("majorCities");
mySpace.cities.names = ["Select","City"];
mySpace.cities.data = [{"name":"Paris"},{"name":"New Delhi"},{"name":"Washington"},{"name":"Bangkok"},{"name":"Sydney"}];
mySpace.cities.draw = function(){
this.pointer.innerHTML="";
var html = "";
html+="<tr>"
for(var i=0;i < this.names.length;i++){
html+="<th>"+this.names[i];
html+="</th>"
}
html+="</tr>"
for(var i=0;i < this.data.length;i++){
html+="<tr>"
html+="<td><input id='"+this.data[i].name+"' type='checkbox'/></td>"
html+="<td>"+this.data[i].name+"</td>"
html+="</tr>"
}
this.pointer.innerHTML=html;
}
mySpace.cities.draw();
mySpace.cities.pointer.addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var city = e.target.id;
console.log(city+":checked="+checked);
}
});
})();
table {width:25%;background:#ccc;border:1px solid black;text-align:left;}
td,tr {background:white;}
th:first-of-type{width:20%;}
<table id="majorCities">
</table>

How to change HTML table cell by clicking and changing last change cell to original using JavaScript – (Switchboard)

I have a HTML table, and each cell has a value “Off”. When a user click on a cell I want to change that value of only that cell to “On” and if the user click another cell change it to “On” put the previously changed cell back to “Off”. Ie. Only one cell shows as “On” and all the others will be “Off”. This must be done using JavaScript and JQuery only (NOT angularJS)
<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>
Here is what I tried:
<script type="text/javascript">
$('#switchboard-container td').click(function ()
{
setClickHandlers();
});
function setClickHandlers() {
// Click handlers that change the content of switches to 'On' or 'Off'.
var cells = document.querySelectorAll('# switchboard -container td');
Array.prototype.forEach.call(cells, function (td) {
td.addEventListener('click', changeCell);
});
}
function changeCell() {
if (this.textContent == "On")
{
this.textContent == "Off";
}
else
{
this.textContent = "On";
}
}
</script>
I can change to “On” but I don’t know how to set other cells to “Off. Can some one please help?
Take a look at this fiddle:
https://jsfiddle.net/3fh4mLba/1/
Basically, adding $(".switch").text("Off"); will set the text to "Off" for all of them before you change it to on.
You can have a simple click handler to do this
$('#switchboard-container td.switch').click(function() {
var $this = $(this);
if ($this.hasClass('on')) { //if the current element is on then we can just make it off
$this.text('Off');
} else {
$this.text('On'); //make the current td on
$('#switchboard-container td.switch.on').removeClass('on').text('Off'); //make other td which are on as off
}
$this.toggleClass('on');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="switchboard-container">
<tbody>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
<tr>
<td class="switch">Off</td>
<td class="switch">Off</td>
</tr>
</tbody>
</table>

Delete duplicate cells of a one column :html

I am to do the same as per This
<table id="test" border="1">
<tr>
<td>test1</td>
<td>test2</td>
<td>test3</td>
</tr>
<tr>
<td>test4</td>
<td>test2</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<td>test2</td>
<td>test9</td>
</tr>
<tr>
<td>test6</td>
<td>test8</td>
<td>test8</td>
</tr>
</table>
LINK of Fiddle
I am able to delete the duplicates from table all columns,but I want to delete duplicate cell values from only first column.
Orginal Output
Remove duplicates from total table getting output as
I want this
Script
var seen = {};
$('#test td:first-child').each(function() {
// Encode column and content information.
var key = $(this).text();
if (seen[key]) {
$(this).text('');
}
else {
seen[key] = true;
}
});
Fiddle Demo
Explanation:
$('#test td:first-child') This helps to select only the first Row of the Table
Use this code it is working fine.
var seen = {};
$('#test td').each(function() {
// Encode column and content information.
var key = $(this).index() + $(this).text();
if (seen[key] && $(this).index()==0) {
$(this).text('');
}
else {
seen[key] = true;
}
});
Fiddle Demo

Categories

Resources