Table cell issue in chrome - javascript

Table .cells will return all the inner cells in table. It is working fine in IE.But in Chrome .cells will return 'undefined' because no such property exists.We have to loop through each row to find the cells.Is there any other way to get all the cells in chrome?
function myFunction() {
var x = document.getElementById("myTable").cells.length;
document.getElementById("demo").innerHTML = "Found " + x + " cells in
the first tr element.";
}
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>

There is nothing called document.getElementById("myTable").cells.length
the .cells actually returns nothing, thus your x variable returns undefined and you don't get the cell numbers.
Instead, you can do the following:
function myFunction() {
var x = document.getElementById("myTable");
// if you need all the cells which is td elements
var cells = x.getElementsByTagName('td');
// if you need only cells in a single row which is a tr element
var cellsPerRow = x.getElementsByTagName('tr')[0].getElementsByTagName('td');
document.getElementById("demo").innerHTML = "Found " + cellsPerRow.length + " cells in the first tr element." + "And " + cells.length + " cells in total" ;
}
myFunction();
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<div id='demo'></div>

Related

Unable to append string content to html table cell with JavaScript

What I need is append html content to a html table cell with jQuery via append method. This is my code,
$('.add_client').click(function(){
var table = document.getElementById("client_table");
var row = table.insertRow(5);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var content = "<strong>Hello</strong>";
cell1.append( content );
cell2.append( content );
});
But appended content looks like <strong>Hello</strong> instead of just Hello. IT will be great if someone can help me on this.
You are using javascript append method not jquery if you want to use jquery append method use it as below $(cell2).append( content )
$('.add_client').click(function(){
var table = document.getElementById("client_table");
var row = table.insertRow(5);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var content = "<strong>Hello</strong>";
$(cell1).append( content );
$(cell2).append( content );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add_client">Add</button>
<table id="client_table">
<tr>
<td>A1</td>
<td>B1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
</tr>
<tr>
<td>A4</td>
<td>B4</td>
</tr>
<tr>
<td>A5</td>
<td>B5</td>
</tr>
<tr>
<td>A6</td>
<td>B5</td>
</tr>
</table>
You are using jQuery append on a DOM node. You need to wrap the cell in $()
$(cell1).append(content);
But since you have jQuery, use it - for example like this
$('.add_client').click(function() {
let $row = $("<tr/>")
let content = "<strong>Hello</strong>";
$row.append($("<td/>").append(content))
$row.append($("<td/>").append(content))
$("#client_table > tbody > tr").eq(4).after($row);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add_client" type="button">Click</button>
<table id="client_table">
<tbody>
<tr>
<td>0</td>
<td>Row 0</td>
</tr>
<tr>
<td>1</td>
<td>Row 1</td>
</tr>
<tr>
<td>2</td>
<td>Row 2</td>
</tr>
<tr>
<td>3</td>
<td>Row 3</td>
</tr>
<tr>
<td>4</td>
<td>Row 4</td>
</tr>
<tr>
<td>5</td>
<td>Row 5</td>
</tr>
</tbody>
</table>
You can use insertAdjacentHTML for appending text as html
cell1.insertAdjacentHTML('beforeend', content);
cell2.insertAdjacentHTML('beforeend', content);
The problem in your case is index. If index is -1 or equal to the number of rows, the row is appended as the last row. If index is greater than the number of rows, an IndexSizeError exception will result. If index is omitted it defaults to -1. about insertRow
$('.add_client').click(function(){
var table = document.getElementById("client_table");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var content = "<strong>Hello</strong>";
cell1.append( content );
cell2.append( content );
});
td {
border: 2px solid green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<input type="button" value="add more" class="add_client"/>
<table id="client_table">
</table>

HTML e JAVASCRIPT table scan

I've a very big table in a HTML page and I create a text input for show only the matching row of the table.
This is my code:
<input type="text" id="myInput" oninput="myFunction()">
<table id="tabella">
<tr><th>TIPO</th><th>SCHEMA</th><th>NOME</th><th>DDL</th></tr>
<tr><td>[...]</td></tr>
[...] > 10000 rows
</table>
<script>
function myFunction() {
var x = document.getElementById("myInput").value;
document.getElementById("demo").innerHTML = "You wrote: " + x;
var table = document.getElementById('tabella');
for (var i = 0, row; row = table.rows[i]; i++)
{
for (var j = 0, col; col = row.cells[j]; j++)
{
$(row).hide();
}
}
for (var i = 0, row; row = table.rows[i]; i++)
{
if ( row.cells[2].innerHTML.includes(x) )
{
$(row).show();
}
}
}
</script>
The problem is:
When I type a single character in the input field it waits for a very long time Is there a mode for rewrite that is faster?
There are several things you can do to improve the performance...
Don't use .innerHTML when the text you are working with doesn't
contain HTML because the browser engages the HTML parser every time
you use this. For getting/setting text that does not contain HTML,
use .textContent. In JQuery, the analogous methods are .html() and .text().
Don't scan the DOM for elements that you've already scanned for
previously. This means make cached variable references to your DOM
objects outside of your repeatedly called functions.
Rather than looping over every row and cell manually, and since you are using
JQuery, just get all the rows into a JQuery wrapped set and work with
that collection. Use the JQuery
.find() method with the JQuery :contains selector.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
#demo { margin-top:1em; padding:3px; width:20%; font-weight:bold;
border:1px solid #aa0; background:#ee3; height:1em;
}
</style>
</head>
<body>
<input type="text" id="myInput">
<table id="tabella">
<thead>
<tr>
<th>TIPO</th>
<th>SCHEMA</th>
<th>NOME</th>
<th>DDL</th>
</tr>
</thead>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 21</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 21</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
</tr>
<tr>
<td>row 3, cell 1</td>
<td>row 3, cell 21</td>
<td>row 3, cell 3</td>
<td>row 3, cell 4</td>
</tr>
<tr>
<td>row 4, cell 1</td>
<td>row 4, cell 21</td>
<td>row 4, cell 3</td>
<td>row 4, cell 4</td>
</tr>
</table>
<div id="demo"></div>
<script>
// Get your DOM references outside of the callback function
// so that you aren't scanning the DOM over and over for the
// same elements.
let $tbl = $("#tabella");
let $dem = $("#demo");
// Don't use inline HTML event handlers (i.e. oninput).
// Do all of yor JavaScript outside of the HTML
$("#myInput").on("input", myFunction);
function myFunction() {
// Hide all the rows in the table, except the header row
// (<tbody> is implicitly created)
$("tbody > tr",$tbl).hide();
// Then, find the row(s) that contain the entered text and show only them.
let $found = $tbl.find("tbody > tr:contains('" + this.value + "')").show();
// Don't use .innerHTML for non-HTML strings, use .textContent instead.
// In JQuery, that's .text() instead of .html()
$dem.text($found.length + " records found.");
}
</script>
</body>
</html>
Thank guys I found the solution:
<script>
var $rows = $('#tabella tr');
$('#myInput').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
</script>

Datatables. How to loop through all rows and get id of each tr entry

This questions targets to Datatables plug-in for JQuery.
I need to loop through all table rows (even paginated) and get id of each tr element.
HTML table like this:
<table>
<thead>
<tr>
<th>Header content 1</th>
<th>Header content 2</th>
</tr>
</thead>
<tbody>
<tr id="etc_1_en">
<td>Etc 1</td>
<td>Etc 2</td>
</tr>
<tr id="etc_1_ru">
<td>Etc 3</td>
<td>Etc 4</td>
</tr>
<tr id="etc_1_fr">
<td>Etc 5</td>
<td>Etc 6</td>
</tr>
<tr id="etc_2_en">
<td>Foo 1</td>
<td>Foo 2</td>
</tr>
<tr id="etc_2_ru">
<td>Foo 3</td>
<td>Foo 4</td>
</tr>
<tr id="etc_2_fr">
<td>Foo 5</td>
<td>Foo 6</td>
</tr>
</tbody>
</table>
So I need to loop through each row and hide row if last 2 characters is not equal to en (with this checking everything fine, I'm using substr).
I can loop through all rows in following:
tbl = $('#myTable').DataTable();
var data = tbl.rows().data();
data.each(function (value, index) {
console.log('Data in index: ' + index + ' is: ' + value);
});
But I can't find a way to get id of tr (with this sample data etc_1_en, etc_1_ru and so on). Could someone help me?
I've tried to pass in function id as parameter, but it returns - undefined.
You can loop through the rows() using rows().every(). This way you will have access to the row object, which will give you both data and id.
tbl = $('#myTable').DataTable();
tbl.rows().every(function () {
var data = this.data();
var id = this.id();
console.log('Data in id: ' + id + ' index: ' + index + ' is: ' + data);
});
More info: https://datatables.net/reference/api/rows().every()

Filter multiple html tables with JS

I'm working on a page with large multiple tables in Html.
To filter them I found and adapted this script that filter for every cell of the table:
<script>
function searchtable() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
th = table.getElementsByTagName("th");
for (i = 1; i < tr.length; i++) {
if (!tr[i].classList.contains('header')) {
td = tr[i].getElementsByTagName("td"),
match = false;
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
break;
}
}
if (!match) {
tr[i].style.display = "none";
} else {
tr[i].style.display = "";
}
}
}
}
</script>
The problem here is that the code work only in the first table of the page and not in the others.
I'd prefer to NOT repeat the script personalizing for every and each table.
Do you have any suggestion on how to personalize the script to look up in multiple tables?
Edit:
Do you know any different script that do the same thing?
I've tried to explain most parts I've changed. In the end the code itsself is a bit shorter, but a tiny bit more complicated. If I made assumptions that aren't correct, let me know. (For example, I'm assuming the 'header' class is only atatched to <tr> elements inside the <thead> who contains <th> elements)
var searchTable = function searchTable(table, input) {
// Since we bound the input, we can use input.value to get the current words typed into the input.
var filter = input.value,
// A table has both a thead and a tbody.
// By only selecting the tr nodes from the body, we can remove the entire 'check if this is a header tr logic of `tr.classList.contains('header')`
// Keep in mind that querySelector returns a nodeList, so if we want to use array methods, we need to covnert it into a real array.
// The original code uses getElementsByTagName, which return a LIVE nodeList, watch out for this difference.
rows = Array.prototype.slice.call(table.querySelectorAll('tbody tr'));
rows.forEach(function(row) {
// Since we don't care in which cell the fitler is contained, we can just check the innerHTML of the entire row.
// This will only fail if the filter typed into the inputs is either 'tr' or 'td'
var hide = (row.innerHTML.indexOf(filter) === -1);
// The alternative is actually checking each cell, but this makes the script take longer:
// var hide = !Array.prototype.slice.call( row.querySelectorAll('td') ).some(function( cell ) {
// return (cell.innerHTML.indexOf( filter ) !== -1);
// });
if (hide) row.classList.add('gone');
else if (row.classList.contains('gone')) row.classList.remove('gone');
});
},
// helper function that we can use to bind the searchTable function to any table and input we want
// We add an onchange event listener, passing it a bound version of searchTable.
bindSearch = function bindSearch(tableID, inputID) {
var input = document.querySelector(inputID),
table = document.querySelector(tableID);
if (table && input) input.addEventListener('change', searchTable.bind(null, table, input));
else alert('Table or input does not exist.');
};
// We can add as many individual inputs / tables as we want by just calling bindSearch with the right ids.
bindSearch('#table1', '#input1');
bindSearch('#table2', '#input2');
.gone {
display: none;
}
<input type="text" id="input1">
<table id="table1">
<thead>
<tr>
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1-1: foo</td>
<td>Cell 1-2: bar</td>
<td>Cell 1-3: baz</td>
<td>Cell 1-4: foo</td>
</tr>
<tr>
<td>Cell 2-1: apples</td>
<td>Cell 2-2: cherries</td>
<td>Cell 2-3: bananas</td>
<td>Cell 2-4: foo</td>
</tr>
<tr>
<td>Cell 3-1: cars</td>
<td>Cell 3-2: bar</td>
<td>Cell 3-3: planes</td>
<td>Cell 3-4: apples</td>
</tr>
<tr>
<td>Cell 4-1: baz</td>
<td>Cell 4-2: 2017</td>
<td>Cell 4-3: 2010</td>
<td>Cell 4-4: 2001</td>
</tr>
<tr>
<td>Cell 5-1: cars</td>
<td>Cell 5-2: 2017</td>
<td>Cell 5-3: foo</td>
<td>Cell 5-4: undefined</td>
</tr>
</tbody>
</table>
<br>
<br>
<input type="text" id="input2">
<table id="table2">
<thead>
<tr>
<th>header 1</th>
<th>header 2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1-1: foo</td>
<td>Cell 1-2: bar</td>
<td>Cell 1-3: baz</td>
<td>Cell 1-4: foo</td>
</tr>
<tr>
<td>Cell 2-1: apples</td>
<td>Cell 2-2: cherries</td>
<td>Cell 2-3: bananas</td>
<td>Cell 2-4: foo</td>
</tr>
<tr>
<td>Cell 3-1: cars</td>
<td>Cell 3-2: bar</td>
<td>Cell 3-3: planes</td>
<td>Cell 3-4: apples</td>
</tr>
<tr>
<td>Cell 4-1: baz</td>
<td>Cell 4-2: 2017</td>
<td>Cell 4-3: 2010</td>
<td>Cell 4-4: 2001</td>
</tr>
<tr>
<td>Cell 5-1: cars</td>
<td>Cell 5-2: 2017</td>
<td>Cell 5-3: foo</td>
<td>Cell 5-4: undefined</td>
</tr>
</tbody>
</table>
html:
<table id="table2">
<thead></thead>
<tbody>
<tr></tr> <tr></tr>
</tbody>
</table>
js:
var table1 = document.getElementById("table1");
var table2 = document.getElementById("table2");
searchtable(table1);
searchtable(table2);
function searchtable(table) {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
tr = table.getElementsByTagName("tr");
th = table.getElementsByTagName("th");
for (i = 1; i < tr.length; i++) {
if (!tr[i].classList.contains('header')) {
td = tr[i].getElementsByTagName("td"),
match = false;
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
match = true;
break;
}
}
if (!match) {
tr[i].style.display = "none";
} else {
tr[i].style.display = "";
}
}
}
}

jQuery functions don't work in Chrome

I did this call in Javascript in IE and it works great but in Chrome NOT at all!
I want to hide or show table rows according to a boolean evaluation.
function show(checked, tableName) {
if (checked) {
$(tableName + " tr.class1").show();
} else {
$(tableName + " tr.class1").hide();
}
}
IN HTML
<input type="checkbox" onclick="show(this.checked, '#tbody1')" />
<table>
<thead></thead>
<tbody id="#tbody1">
<tr class="class1"><td></td></tr>
<tr><td></td></tr>
<tr class="class1"><td></td></tr>
<tr><td></td></tr>
</tbody>
</table>
Nothing happens.
Foolish problem! It works now! It was a problem of Chrome temporary files. It was running the previous version of my javascript which was an include!. Thank you all you guys for the time.
This script I wrote works for me:
var tableClass = '.table';
var checked = false;
if(checked){
$(tableClass + " tr.class1").show();
}else{
$(tableClass + " tr.class1").hide();
}
Having this html:
<table class='table' border="1">
<tr class='class1'>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

Categories