I want give every element in a table a generated id. See this html table below:
<table>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>
A3
</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>
B3
</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
</tr>
</tbody>
</table>
I want to give each element an id using breadth-first traversal. So, the result becomes like this:
<table>
<tbody id="0">
<tr id="1">
<td id="4">A1</td>
<td id="5">A2</td>
<td id="6">
A3
</td>
</tr>
<tr id="2">
<td id="7">B1</td>
<td id="8">B2</td>
<td id="9">
B3
</td>
</tr>
<tr id="3">
<td id="10">C1</td>
<td id="11">C2</td>
<td id="12">C3</td>
</tr>
</tbody>
</table>
I have tried the each() function in jQuery to generate the id for every element in that table, but the traversal algorithm used in each() function is pre order traversal.
Can anyone suggest me the Javascript code to do this?
var n = 0
var level = $("table");
while (level.children().length) {
level = level.children().each(function(_, el) {
el.id = n++;
})
}
DEMO: http://jsfiddle.net/J5QMK/
If you want to avoid the redundant .children() call, you can do this:
while ((level = level.children()).length) {
level.each(function (_, el) {
el.id = n++;
})
}
DEMO: http://jsfiddle.net/J5QMK/1/
A common way to do a breadth-first search is to use a queue as follows:
jQuery(document).ready(function () {
var ctr = 0;
var queue = [];
queue.push(jQuery("table").children()); // enqueue
while (queue.length > 0) {
var children = queue.shift(); // dequeue
children.each(function (ix, elem) {
queue.push( // enqueue
jQuery(elem).attr("id", ctr++).children();
);
console.log(elem.tagName + ": " + elem.id);
});
}
});
Related
I have this counter for word occurrence in the textarea. The problem is, I have a lot of items in the table, and so it can be distracting to include the zero results.
So what I'm hoping to achieve is, if the user checks the checkbox, it will not show the zero results anymore (preferably the whole row)..
Please see the code so far:
let textarea = $('#textarea3');
textarea.on('keyup', _ => counting());
function counting() {
var searchText = $('#textarea3').val();
let words = [];
words['1 sample'] = '#one';
words['2 sample'] = '#two';
words['3 sample'] = '#three';
words['4 sample'] = '#four';
words['5 sample'] = '#five';
words['6 sample'] = '#six';
for (const word in words) {
var outputDiv = $(words[word]);
outputDiv.empty();
let count = searchText.split(word).length - 1;
searchText = searchText.replaceAll(word,'');
outputDiv.append('<a>' + count + '</a>');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox">
<label> Don't show zero results</label><br>
<button onclick="counting();">Count</button>
<table>
<thead>
<tr>
<th scope="col">Items</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 sample</td>
<td><a id="one"></a></td>
</tr>
<tr>
<td>2 sample</td>
<td><a id="two"></a></td>
</tr>
<tr>
<td>3 sample</td>
<td><a id="three"></a></td>
</tr>
<tr>
<td>4 sample</td>
<td><a id="four"></a></td>
</tr>
<tr>
<td>5 sample</td>
<td><a id="five"></a></td>
</tr>
<tr>
<td>6 sample</td>
<td><a id="six"></a></td>
</tr>
</tbody>
</table>
<textarea id="textarea3" rows="5">
1 sample
2 sample
3 sample
5 sample
</textarea>
If the checkbox isn't checked, it should function as is and still show all results.
I've seen this post but I'm not really sure how to implement it to my own project. Show or hide table row if checkbox is checked
Thank you in advance for any help.
Consider the following.
$(function() {
var textarea = $('#textarea3');
var words = [];
$("table tbody tr").each(function(i, row) {
words.push({
term: $("td:eq(0)", row).text().trim(),
rel: "#" + $("a", row).attr("id"),
count: 0
});
});
function count() {
var searchText = textarea.val();
$.each(words, function(i, word) {
if (searchText.indexOf(word.term) >= 0) {
var re = new RegExp('(' + word.term + ')', 'gi');
word.count = searchText.match(re).length;
$(word.rel).html(word.count);
} else {
word.count = 0;
if (!$("#noShowZero").is(":checked")) {
$(word.rel).html(word.count);
} else {
$(word.rel).html("");
}
}
});
}
textarea.keyup(count);
$("#count-btn, #noShowZero").click(count);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="noShowZero" type="checkbox">
<label> Don't show zero results</label><br>
<button id="count-btn">Count</button>
<table>
<thead>
<tr>
<th scope="col">Items</th>
<th scope="col">Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 sample</td>
<td>
<a id="one"></a>
</td>
</tr>
<tr>
<td>2 sample</td>
<td>
<a id="two"></a>
</td>
</tr>
<tr>
<td>3 sample</td>
<td>
<a id="three"></a>
</td>
</tr>
<tr>
<td>4 sample</td>
<td>
<a id="four"></a>
</td>
</tr>
<tr>
<td>5 sample</td>
<td>
<a id="five"></a>
</td>
</tr>
<tr>
<td>6 sample</td>
<td>
<a id="six"></a>
</td>
</tr>
</tbody>
</table>
<textarea id="textarea3" rows="5">
1 sample
2 sample
3 sample
5 sample
</textarea>
When the User:
Enters text in the textbox
Clicks the checkbox
Clicks the Button
then count function is executed.
Count will review all the words and look for specific keywords. A count of them is also retained, as well as element relationship to show that count.
Using Regular Expressions, we can search for the words in the text and count them using .match(). It returns an Array of the matches. You could also use .replace(), to remove them.
How do you convert an HTML table to a javascript array using the tags's class names as the array values?
Say we have the following HTML code:
<table class="grid">
<tr>
<td class="available"></td>
<td class="busy"></td>
<td class="busy"></td>
<td class="available"></td>
</tr>
<tr>
<td class="busy"></td>
<td class="available"></td>
<td class="busy"></td>
<td class="available"></td>
</tr>
</table>
I want the array to look like: [["available","busy","busy","available"],["busy","available","busy","available"]]
I have tried the following:
var myTableArray = [];
$("table#grid tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
console.log(myTableArray);
but it is printing an empty array as the td tags contain no text. I then tried replacing
$(this).text()
with
$(this).className()
but that did not work. Any suggestions?
map is the way to go.
jQuery's $.map is a little weird in that it seems to think it's ok to flatten mapped arrays without asking and we're not going to fix it so you have to couch the mapped array in an array.
// Cache the rows
const rows = $('.grid tr');
// `map` over each row...
const arr = $.map(rows, row => {
// Find the row cells...
const cells = $(row).find('td');
// ...and return an array of each cell's text
return [$.map(cells, cell => $(cell).text())];
});
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="grid">
<tr>
<td class="available">available</td>
<td class="busy">busy</td>
<td class="busy">busy</td>
<td class="available">available</td>
</tr>
<tr>
<td class="busy">busy</td>
<td class="available">available</td>
<td class="busy">busy</td>
<td class="available">available</td>
</tr>
</table>
Alternatively, if you wanted a vanilla JS solution, you can just pick up the rows with querySelectorAll, and then iterate over them with map, then return the text from the cell (assuming that you fix the HTML).
(Note: [...nodelist] is shorthand for creating an array from a nodelist so that map can work. You could also use Array.from(nodelist)).
// Cache the rows
const rows = document.querySelectorAll('.grid tr');
// `map` over each row...
const arr = [...rows].map(row => {
// Find the row cells...
const cells = row.querySelectorAll('td');
// ...and return an array of each cell's text
return [...cells].map(cell => cell.textContent);
});
console.log(arr);
<table class="grid">
<tr>
<td class="available">available</td>
<td class="busy">busy</td>
<td class="busy">busy</td>
<td class="available">available</td>
</tr>
<tr>
<td class="busy">busy</td>
<td class="available">available</td>
<td class="busy">busy</td>
<td class="available">available</td>
</tr>
</table>
Vanilla JS Solution
Get and Make array with <tr>
Map every <tr> and make array with <td> elements
Map only class names from every <td>
The example will return ARRAY from CLASS element names.
Example:
var res = [...document.querySelectorAll('.grid tr')] // 1. Get and Make array with <tr>
.map((el) => [...el.children] // 2. Map every <tr> and make array with <td> elements
.map(e => e.getAttribute('class'))); // 3. Map only class names from every <td>
console.log(res);
<table class="grid">
<tr>
<td class="available"></td>
<td class="busy"></td>
<td class="busy"></td>
<td class="available"></td>
</tr>
<tr>
<td class="busy"></td>
<td class="available"></td>
<td class="busy"></td>
<td class="available"></td>
</tr>
</table>
This example will make ARRAY from the text content of the table.
Example:
var res = [...document.querySelectorAll('.grid tr')] // 1. Get and Make array with <tr>
.map((el) => [...el.children] // 2. Map every <tr> and make array with <td> elements
.map(e => e.innerText)); // 3. Map only text content from every <td>
console.log(res);
<table class="grid">
<tr>
<td>available</td>
<td>busy</td>
<td>busy</td>
<td>available</td>
</tr>
<tr>
<td>busy</td>
<td>available</td>
<td>busy</td>
<td>available</td>
</tr>
</table>
I have a page with several rows containing information, made by several users. I'm looking for a way to highlight the all the users rows on mouseover.
This "Highlight multiple items on hover's condition" almost solved my problem, but since the classes or id's in my problem are dynamic from a database, and would contain an identifier from the DB and are unique each time. I have not been able to apply it.
Example code: https://jsfiddle.net/3cehoh78/
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2a</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4a</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
</table>
<br>
<br>
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1b</td>
<td class="cellclass">Sauron</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4b</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 5b</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
</table>
In this example, I want all the rows with "Sam" to be highlighted on mouseover on one of them, so rows 1a,3a,2b,3b.
I was thinking of adding a class to all the Sam rows when generating the tables (Sam has a unique user ID), but how do I then change css that affects all the rows on mouseover (and not just one).
Please note that I cant pre-add css classes for all the unique userID's, this is just an example.
Here a solution with JQuery https://jsfiddle.net/3cehoh78/5
$(document).ready(function() {
$( "tr" ).hover(function() {
var search = $(this).find("td:eq(1)").text();
$( ".highlight" ).removeClass("highlight");
$("tr:contains('"+search+"')").addClass("highlight");
}); /* END HOVER */
}); // end document ready
Simple solution without using jQuery and co: https://jsfiddle.net/3cehoh78/3/
var rows = [].slice.call(document.querySelectorAll('.testtable tr'));
rows.forEach(function(row) {
row.addEventListener('mouseover', function() {
resetHighlighting();
var name = row.querySelector('td:nth-child(2)').textContent;
rows.forEach(function(r) {
if (r.querySelector('td:nth-child(2)').textContent === name) {
r.classList.add('highlighted');
}
});
});
});
function resetHighlighting() {
rows.forEach(function(row) {
row.classList.remove('highlighted');
});
}
Here's another way using vanilla-JavaScript.
var tds = document.querySelectorAll('td');
var highlight = function () {
// take this person's name from the 2nd cell
var name = this.parentNode.children[1].innerHTML;
// highlight cells with same name
tds.forEach(function (td) {
var tr = td.parentNode;
// compare other's person name with this person name
// highlight if there is a match
tr.classList.toggle('highlight', tr.children[1].innerHTML === name)
});
}
// attach an event listener to all cells
tds.forEach(function (td) {
td.onmouseover = highlight;
});
Demo
I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)
I want to multiply cells content (only numbers) and using javascript.
The result is to be displayed in cell X
<script type="text/javascript">
function zmiana(){
var x = document.getElementById("rowstawka");
x.getElementsByTagName('td')[1].innerHTML=document.getElementById('Stawka2').value;
var y = document.getElementById("rowgodziny");
y.getElementsByTagName('td')[1].innerHTML=document.getElementById('Godziny').value;
}
</script>
I'm using the above script to add content to cells in a table.
And here is the table:
<table id="tabela">
<tr id="rowstawka">
<td>Stawka</td>
<td>12</td>
</tr>
<tr id="rowgodziny">
<td>Godziny</td>
<td>50</td>
</tr>
<tr id="rowPensja">
<td>Pensja</td>
<td>-</td>
</tr>
<tr id="rowNetto">
<td>Pensja Netto</td>
<td>x</td>
</tr>
</table>
If you can change the html, try using classes to determine which cells contains a number to be calculated:
<table id="tabela">
<tr id="rowstawka">
<td>Stawka</td>
<td class="num">12</td>
</tr>
<tr id="rowgodziny">
<td>Godziny</td>
<td class="num">50</td>
</tr>
<tr id="rowPensja">
<td>Pensja</td>
<td>-</td>
</tr>
<tr id="rowNetto">
<td>Pensja Netto</td>
<td id="result">x</td>
</tr>
</table>
Then use this simple snippet to make the magic:
var numbers = document.querySelectorAll(".num");
var total = 1;
for (var i = 0; i < numbers.length; i++)
{
total*= Number(numbers[i].innerText);
}
document.getElementById("result").innerText = total;
Fiddle