Filtering results in a table - javascript

I have a PHP page and a table where I fill it up with data from the database. I have a search field on top of the table where I would like to filter rows as I am typing.
Here is my Javascript
$('#system-search').keyup( function()
{
var that = this;
// affect all table rows on in systems table
var tableBody = $('.table table-filter tbody');
var tableRowsClass = $('.table table-filter tbody tr');
$('.search-sf').remove();
tableRowsClass.each( function(i, val)
{
//Lower text for case insensitive
var rowText = $(val).text().toLowerCase();
var inputText = $(that).val().toLowerCase();
if(inputText != '')
{
$('.search-query-sf').remove();
tableBody.prepend('<tr class="search-query-sf"><td colspan="6"><strong>Searching for: "'
+ $(that).val()
+ '"</strong></td></tr>');
}
else
{
$('.search-query-sf').remove();
}
if( rowText.indexOf( inputText ) == -1 )
{
//hide rows
tableRowsClass.eq(i).hide();
}
else
{
$('.search-sf').remove();
tableRowsClass.eq(i).show();
}
});
//all tr elements are hidden
if(tableRowsClass.children(':visible').length == 0)
{
tableBody.append('<tr class="search-sf"><td class="text-muted" colspan="6">No entries found.</td></tr>');
}
});
Sorry for the bad code and formatting I can't seem to understand how to format it properly..

https://stackoverflow.com/a/19696936/1406155
You are using a bit too much code for that. First place an input field like this
<input type="text" id="search" placeholder="Search">
and use the below function for search
$("#search").keyup(function () {
var value = this.value.toLowerCase().trim();
$("table tr").each(function (index) {
if (!index) return;
$(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;
});
});
});

Related

Download filtered html table data to csv file

I created an ejs file that can display the documents in the mongodb db collection into the table, and I added select:option that can filtered the table. for example, select:option of date I choose 05/28/2019 it will only display data with 05/28/2019 date. and I already have a download form that can download the table, However the download button only download the whole data in the table and cannot download the filtered data. My question is if there is a way that once I filtered the data in the table and I click download it will only download the filtered data not the whole table. Please see the sample code here https://jsfiddle.net/indefinite/b63y928L/9/
this is the code that can filter the table
$(document).ready(function () {
$('.filter').change(function () {
var values = [];
$('.filter').each(function () {
var colIdx = $(this).data('col');
$(this).find('option:selected').each(function () {
if ($(this).val() != "") values.push( {
text: $(this).text(),
colId : colIdx
});
});
});
filter('table > tbody > tr', values);
});
function filter(selector, values) {console.log(values);
$(selector).each(function () {
var sel = $(this);
var tokens = sel.text().trim().split('\n');
var toknesObj = [], i;
for(i=0;i<tokens.length;i++){
toknesObj[i] = {
text:tokens[i].trim(),
found:false
};
}
var show = false;
//console.log(toknesObj);
$.each(values, function (i, val) {
if (toknesObj[val.colId].text.search(new RegExp("\\b"+val.text+"\\b")) >= 0) {
toknesObj[val.colId].found = true;
}
});
console.log(toknesObj);
var count = 0;
$.each(toknesObj, function (i, val) {
if (val.found){
count+=1;
}
});
show = (count === values.length);
show ? sel.show() : sel.hide();
});
}
and this is what I followed on how to download the html table to csv file https://codepen.io/malahovks/pen/gLxLWX?editors=1010
I expect that once I select a date it will only download the data in the date that I selected. Thank you!
You can modify the row selector to select only visible rows. var rows = $("table tr:visible");. Since you are already using jquery library, you can use the jquery selector.
function export_table_to_csv(html, filename) {
var csv = [];
//var rows = document.querySelectorAll("table tr:visible");
var rows = $("table tr:visible");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
// Download CSV
download_csv(csv.join("\n"), filename);
}
See the updated fiddle https://jsfiddle.net/165yj7se/

Hide entire column(s) right of specific column accounting for rowspans and colspans

I have this table http://codepen.io/MetCastle/pen/lxceL and I want to hide/show the columns depending on an input type="number" using jQuery. mean this entire columns:
Proveedor 1
Proveedor 2
Proveedor 3
Proveedor 4
Proveedor 5
Proveedor 6
I don't know how to do that. I have tried :nth-child() Selector, but I don't understand how works.
I made this function but obviously it is incomplete:
$(document).ready(function() {
if ($( ".size").val() == 1)
// hide Proveedor 1
else if ($( ".size").val() == 2)
// hide Proveedor 2
});
Pretty flexibly accounting for colspans here... I think this will work for you:
JSFiddle: (I put 2 in the .size value so you will see it removes the "Proveedor 2" and the columns under it, you can change this in the HTML section of the fiddle to test with different numbers)
$(document).ready(function () {
var column = 0;
var colspan;
$("tr").eq(0).find("th").each(function () {
$this = $(this);
if ($.trim($this.text()) === "Proveedor "+$(".size").val()) {
$this.hide();
colspan = +$this.attr("colspan") || 1;
return false;
}
column += +$this.attr("colspan") || 1;
});
$("tr:gt(0)").each(function () {
var currCol = 0;
$(this).find("td, th").each(function () {
$this = $(this);
if (column === currCol) {
$this.hide();
for(i = +$this.attr("colspan") || 1; i < colspan;) {
$this = $this.next();
$this.hide();
i += +$this.attr("colspan") || 1;
}
return false;
}
currCol += +$this.attr("colspan") || 1;
});
});
});
Note:
+$this.attr("colspan") || 1
The + in front is to convert this into a number (from a string). If colspan is undefined it will equate to a falsey value (NaN) which will then move on to the 1 (which is the default if colspan isn't defined)... so if colspan is defined it will be whatever was defined, otherwise it will be 1.
After clarifying some requirements, here is a modification. The code gets pretty complex to deal with both colspans and rowspans....
JSFiddle
$(":input").on('change', function () {
$("td, th").show();
var column = 0;
var colspan = 0;
var rowspanning = [];
$("tr").eq(0).find("th").each(function () {
$this = $(this);
if ($.trim($this.text()) === "Proveedor " + $(".size").val()) {
$this.nextAll().hide();
colspan = +$this.attr("colspan") || 1;
rowspanning[column] = $this.attr("rowspan")-1 || 0;
return false;
}
column += +$this.attr("colspan") || 1;
});
if (column) {
$("tr:gt(0)").each(function () {
var currCol = 0;
$(this).find("td, th").each(function () {
$this = $(this);
if(rowspanning[currCol] > 0) {
--rowspanning[currCol];
++currCol;
}
rowspanning[currCol] = $this.attr("rowspan")-1 || 0;
if (column === currCol) {
for (i = +$this.attr("colspan") || 1; i < colspan;) {
$this = $this.next();
i += +$this.attr("colspan") || 1;
}
$this.nextAll().hide();
return false;
}
currCol += +$this.attr("colspan") || 1;
});
});
}
});
Use the :nth-child() selector to hide the "nth" element after the tr element for each row. For example,
if ($( ".size").val() == 1){
$('tr td:nth-child(1)').hide();
//include this line only if you also have a thead element with headings
$('tr th:nth-child(1)').hide();
}
else if ($( ".size").val() == 2){
$('tr td:nth-child(2)').hide();
//include this line only if you also have a thead element with headings
$('tr th:nth-child(2)').hide();
}

How to display one row from a HTML table and change to next?

I have a HTML table with 2 columns, 5 rows.
you can do this:
function findMyRow(el)(){
if(!el.parentNode) return null;
else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
tbl.rows[i].onclick = function(e){
var selectedRow = null;
if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
selectedRow = findMyRow(e.target);
//this is just for preventing false event raising
if(!selectedRow) return false;
var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
for(car j=0;j<selectedRow.cells.length;j++){
var cell = selectedRow.cells[j];
//let's say your inputs each has an unique ID based on your columns index
//like <input id="cellData0" ttype="text" />
//or <input id="cellData1" ttype="text" /> and so on
document.getElementById("cellData" + j).value = cell.innerText;
}
}
}
although you can do this more easier than with jQuery.
With Jquery you could do something like:
$(document).ready(function(){
window.rowIndex = 0; // gobal variable
function displayRow(){
var tableRows = $('#mytable tr');
if(tableRows.length <= window.rowIndex) {
window.rowIndex = 0;
}
var rowCells = $(tableRows[window.rowIndex]).find('td');
$('.cellone').val($(rowCells[0]).html());
$('.celltwo').val($(rowCells[1]).html());
window.rowIndex = window.rowIndex + 1;
};
$('.next').click(function(event){ displayRow(); });
displayRow();
});
There is a live demo here Hope it helps!

How to highlighted the selected row from repeater?

I have a repeater, and i just want that when i select or click on any row of it then that would be highlighted. I had tried some code of javascript which makes the selected row highlighted, but not unhighlighting when select any other row.My code is:-
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
any javascript's and style's code is:-
<style type="text/css">
.highlight
{
background-color: Red;
}
.selected
{
background-color: #ffdc87;
}
</style>
<script type="text/javascript">
function Select(obj) {
obj.className = 'selected';
var tbl = document.getElementById("Repaddressorbbl")
var firstRow = tbl.getElementsByTagName("TR")[0];
var tableRowId = tbl.rows[firstRow.getElementById("gh").parentNode.id];
alert(tableRowId);
var oldRow = tbl.rows[firstRow.getElementsByTagName("tr")[0].value];
if (oldRow != null) {
oldRow.className = '';
}
firstRow.getElementsByTagName("tr")[0].value = obj.rowIndex;
}
</script>
We can do it simply with code behind but the matter is it should be done only with jquery or javascript.
You can use code similar to this:
var INDEX = $(this).parent().children().index($(this));
$('#Repaddressorbbl tr:nth-child(' + INDEX + ')').addClass("highlight")
.siblings()
.removeClass("highlight"); // remove css class from other rows
It gets the rownumber of the TR and adds a CSS class while removing the same class from all other TRs.
i've added a function to select elements with a specific classname so you can easly search the dom for elements with that class
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
function Select(obj) {
var oldRow = document.getElementsByClassName('selected');
if(oldRow.length > 0)
oldRow[0].className = '';
obj.className = 'selected';
}
Update for jQuery:
$(document).ready(function() {
$("tr").click(function() {
$(this).addClass("highlight").siblings().removeClass("highlight");
}
}
Original answer:
If I understand you correctly, all of your table rows are defined like this:
<tr id="gh" style="cursor: pointer" onclick="Select(this);">
And you want to set a class on the most recently clicked row so it looks selected, while clearing said class from the previously clicked/selected row?
If so, a much simplified version of your function should do it:
var selectedRow = null;
function Select(obj) {
if (obj != selectedRow) {
if (selectedRow != null) {
selectedRow.className = '';
}
obj.className = 'selected';
selectedRow = obj;
}
}
I don't understand what you're trying to do with the firstRow.getElementsByTagName("tr") stuff. Have you got nested tables?

How do I remove an element from the DOM, given its id?

In this specific case, the element is a table row.
Untested but something like:
var tbl = document.getElementById('tableID');
var row = document.getElementById('rowID');
tbl.removeChild(row);
or
var row = document.getElementById('rowID');
row.parentNode.removeChild(row);
var row = document.getElementById("row-id");
row.parentNode.removeChild(row);
var zTag = document.getElementById ('TableRowID');
zTag.parentNode.removeChild (zTag);
Or in jQuery:
$('#TableRowID').remove ();
Jquery
$('#myTableRow').remove();
This works fine if your row has an id, such as:
<tr id="myTableRow"><td>blah</td></tr>
Pure Javascript :
Javascript Remove Row From Table
function removeRow(id) {
var tr = document.getElementById(id);
if (tr) {
if (tr.nodeName == 'TR') {
var tbl = tr; // Look up the hierarchy for TABLE
while (tbl != document && tbl.nodeName != 'TABLE') {
tbl = tbl.parentNode;
}
if (tbl && tbl.nodeName == 'TABLE') {
while (tr.hasChildNodes()) {
tr.removeChild( tr.lastChild );
}
tr.parentNode.removeChild( tr );
}
} else {
alert( 'Specified document element is not a TR. id=' + id );
}
} else {
alert( 'Specified document element is not found. id=' + id );
}
}

Categories

Resources