Read all td values with Javascript - javascript

I am trying to get all td and compare each td value to a string .
but my code only reads the first td of each tr.
Here is my HTML :
<table border="2px" id="tab">
<tr>
<td>color</td>
<td> a </td>
<td> font</td>
<td>123</td>
</tr>
<tr>
<td>font</td>
<td> color </td>
</tr>
<tr>
<td>a</td>
<td> color</td>
<td> font</td>
</tr>
<tr>
<td>font</td>
</tr>
</table>
My js code:
var t=["color","font","a"];
function color()
{
var colr=0;
var tab=[];
var table = document.getElementById("tab");
var len=table.rows.length;
for (var i = 0; i< len; i++)
{
for (var j=0; j<table.rows[i].cells.length; j++)
{
tab[j]= table.rows[i].cells[j].innerHTML;
// alert(tab[j]);
if(tab[j]== t[0])
{ colr++;}
}
}
alert(colr);
}
What am I missing?

The spacing in the <td> is messing with the comparisons. As your code lies, you're comparing " color" to "color" and that's returning false, thus seeing as you're only getting that colr index going up to 1.
You'll need to strip out the spaces in order to compare properly, example JSFiddle here: https://jsfiddle.net/76q3aro3/

Related

How to find the value from a row of table depending on the row of a button I clicked

No jQuery involve pls. I am just started learning javascript.
I want to find the class='id' of the table when I clicked on the class='detail' button.
I manage to point to class='id' but I can't get the value out of it, why?
var button = document.getElementsByClassName("detail");
for (var i in button) {
button[i].onclick = function() {
var row = this.closest("tr");
var id = row.getElementsByClassName("id");
var value = id.innerText;
console.log(id);
console.log(value); //show undefined here
}
}
<table>
<tbody>
<tr>
<td class="id">123</td>
<td class="name">abc</td>
<td><button class="detail">detail</button></td>
</tr>
<tr>
<td class="id">456</td>
<td class="name">def</td>
<td><button class="detail">detail</button></td>
</tr>
</tbody>
</table>
where would need to change? I must use class here, as the table generated through javascript. thanks.
getElementsByClassName returns HTMLCollection containing multiple matching elements. Like an array, you can access the first element in the collection with [0]
var button = document.getElementsByClassName("detail");
for (var i in button) {
button[i].onclick = function () {
var row = this.closest("tr");
var id = row.getElementsByClassName("id");
var value = id[ 0 ].innerText;
console.log(id);
console.log(value);
}
}
<table>
<tbody>
<tr>
<td class="id">123</td>
<td class="name">abc</td>
<td><button class="detail">detail</button></td>
</tr>
<tr>
<td class="id">456</td>
<td class="name">def</td>
<td><button class="detail">detail</button></td>
</tr>
</tbody>
</table>

Print array in the table td

I am new in Javascript, I have an array, and want to print it in the table td.
This is my array:
array = [100, 200, 300];
This is my table:
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
I want to print my array in the td with class name 'result'
You can use querySelectorAll() and Node.textContent:
const array = [100, 200, 300];
const elements = [...document.querySelectorAll('.result')];
for(let i = 0; i < array.length; i++) {
elements[i].textContent = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Just iterate over the array and use the current index for the HTML element as well.
Possible ES5-only solution:
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
document.getElementsByClassName("result")[i].innerHTML = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Note: You need an equal amount of array elements and elements with the .result class.
Assign an id attribute to the table tag, id = "tab". Then add the below javascript code
pointer=0
arr=[100,200,300];
// selecting all the tags having result as class name
var nodes=document.getElementById("tab").getElementsByClassName("result");
arr.forEach((ele)=>{nodes[pointer].innerHTML=ele;pointer+=1});
Look at this example:
I use querySelectorAll
It considers the case if the array elements and the quantity of rows are diffrerent.
Also added '.myTable' to prevent target other '.result' nodes out of the selected table.
Hope it helps.
<table class="myTable">
<th> Result</th>
<tbody>
<tr><td> My result 1</td><td class='result'></td></tr>
<tr><td> My result 2</td><td class='result'></td></tr>
<tr><td> My result 3</td><td class='result'></td></tr>
<tr><td> My result 4</td><td class='result'></td></tr>
</tbody>
</table>
<script>
const array = [100, 200, 300];
const rows = document.querySelectorAll('.myTable .result') // <-- I added '.myTable' to prevent target other '.result' nodes out of the selected table
rows.forEach((row, i) => {
if (array[i]) row.innerHTML = array[i] // <-- I replace the innerHTML if the array has content at that index
});
</script>
You can do this,
var result = document.getElementsByClassName("result")
var array = [100,200,300]
for (var i=0;i<result.length;i++){
result[i].innerHTML = array[i];
}
Demo
Hope this helps you... No need to update table according to array data....
Table code:
<table>
<th colspan="2" >Result</th>
<tbody id="myTableBody"></tbody>
</table>
JavaScript code:
<script>
var tableRef = document.getElementById('myTableBody');
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
tableChild = document.createElement('tr');
tableChild.innerHTML = "<td> My result "+(i+1)+"</td><td class='result'>"+array[i]+"</td>";
tableRef.appendChild(tableChild);
}
</script>
Example: https://codepen.io/Nishanth_V/pen/rEZmxN
var el = document.getElementsByClassName('result');
var array = [100, 200, 300];
for(var i =0 ; i < el.length && i < array.length; ++i) {
el[i].innerHTML = array[i];
}
You have to replace ' by " and add numbers to your class , after that your code with look like this:-
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class="result1"></td>
</tr>
<tr>
<td> My result 2</td>
<td class="result2"></td>
</tr>
<tr>
<td> My result 3</td>
<td class="result3"></td>
</tr>
</tbody>
</table>
Your JavaScript code will look like this:-
<script>
var array = [100, 200, 300];
array.foreach(function (item, index){
var resultNum = index + 1;
document.getElementByClassName("result" + resultNum).innerHTML = item;
});
</script>

html table with javascript sp

Basically, I am a beginner who recently started working with Javascript and I want to simplify my code. How can I simplify this? How would I apply a loop because it is too long to declare it by a single code if I want to change the id. Not manually changing in the html, but using a Javascript to change the value in html?
<table border="2" cellpadding="4">
<tbody>
<tr>
<td id="cell1"> one </td>
<td id="cell2"> two </td>
<td id="cell3"> three </td>
</tr>
<tr>
<td id="cell4"> four </td>
<td id="cell5"> five </td>
<td id="cell6"> six </td>
</tr>
</tbody>
</table>
document.getElementById("cell1").innerHTML="1";
document.getElementById("cell2").innerHTML="2";
document.getElementById("cell3").innerHTML="3";
document.getElementById("cell4").innerHTML="4";
document.getElementById("cell5").innerHTML="5";
document.getElementById("cell6").innerHTML="6";
try this code using for loop
var items = document.getElementsByTagName('td');
for (var i = 0, j = 1; i <= items.length - 1; i++, j++) {
items[i].innerHTML = j;
}
<table border="2" cellpadding="4">
<tbody>
<tr>
<td id="cell1"> one </td>
<td id="cell2"> two </td>
<td id="cell3"> three </td>
</tr>
<tr>
<td id="cell4"> four </td>
<td id="cell5"> five </td>
<td id="cell6"> six </td>
</tr>
</tbody>
</table>
i hope that help you and you can start learn javascript on this site https://www.w3schools.com/js/ is very useful:
var d = document;
var trs = d.getElementsByTagName("tr");
console.log(trs);
var count = 1;
for(var i=0 ; i<trs.length ; i++){
tds = trs[i].getElementsByTagName("td");
for(var j=0 ; j<tds.length ; j++){
tds[j].innerHTML = count;
count++;
}
console.log(trs[i]);
}

Sum table values based on grouping

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)

Remove table row by finding content with clause

I have this code:
<table>
<tbody>
<tr><td>Table 1</td></tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td align="left">Number</td>
<td><b>33</b></td>
</tr>
<tr>
<td width="150" align="left">Field</td>
<td>XXXX</td>
</tr>
<tr>
<td align="left">Select: </td>
<td colspan="4">
<select name="status" size="1">
<option selected="selected" value="2">one</option>
<option value="1">two</option>
</select>
</td>
</tr>
</tbody>
</table>
and i want to remove this line by searching "Field" with pure Javascript:
<tr>
<td width="150" align="left">Field</td>
<td>XXXX</td>
</tr>
when there is a 33, 66 or 99 in this line from my 2nd table:
<tr>
<td align="left">Number</td>
<td>33</td>
</tr>
The problem is that i don't have any id's or classes for identification! i want to use the code with Greasemonkey.
Here you can see a JSFIDDLE of my table.
And here you can see on JSFIDDLE how it should look.
Best regards bernte
Here you go:
var disallowedValues = ['33', '66', '99'];
var cols = document.getElementsByTagName('td');
var colslen = cols.length;
var i = -1;
var disallowedTable;
while(++i < colslen){
// look for the td where the disallowed values are
if(disallowedValues.indexOf(cols[i].innerHTML) >= 0)
{
// get the table where the disallowed values is
disallowedTable = cols[i].parentNode.parentNode.parentNode;
// break the cicle to stop looking for other rows
//break;
}
}
// look for the 'Field' value only on the table that has the disallowed value
var cols = disallowedTable.getElementsByTagName('td');
cols = disallowedTable.getElementsByTagName('td');
colslen = cols.length;
i = -1;
while(++i < colslen){
// look for the td where the 'Field' value is
if(cols[i].innerHTML == 'Field')
{
// get the tr for such td
var deletionTR = cols[i].parentNode;
//delete that tr
deletionTR.parentNode.removeChild(deletionTR);
// break the cicle to stop looking for other rows
break;
}
}
You can always do a simpler version if jquery is an option.

Categories