html table with javascript sp - javascript

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]);
}

Related

Read all td values with 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/

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)

How to multiply the contents of table cells via js?

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

Trouble with IDs and for loops in Javascript

$(document).ready(function() {
var week = 5;
var players = 8;
var numbers = [];
var array = [];
for (o = 0; o < players; o++) {
for (i = 0; i < week + 1; i++) {
var improved = i + 1;
var oString = o.toString();
var iString = i.toString();
var id = "#" + oString + iString;
var rawText = $(id).text();
var refined = Number(rawText);
array.push(refined);
}
numbers.push(array);
array = [];
}
for (p = 0; i < numbers.length; p++) {
var total1 = 0;
$.each(numbers[0], function() {
total1 += this;
});
}
$("#total1").text(total1);
for (p = 0; i < numbers.length; p++) {
var total2 = 0;
$.each(numbers[0], function() {
total2 += this;
});
}
$("#total2").text(total2);
for (p = 0; i < numbers.length; p++) {
var total3 = 0;
$.each(numbers[0], function() {
total3 += this;
});
}
$("#total3").text(total3);
for (p = 0; i < numbers.length; p++) {
var total4 = 0;
$.each(numbers[0], function() {
total4 += this;
});
}
$("#total4").text(total4);
for (p = 0; i < numbers.length; p++) {
var total5 = 0;
$.each(numbers[0], function() {
total5 += this;
});
}
$("#total5").text(total5);
var total = total1 + total2 + total3 + total4 + total5;
$("#total").text(total);
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="jquery-1.11.1.min.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="style2.css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon">
<link rel="icon" href="../favicon.ico" type="image/x-icon">
</head>
<body>
<table>
<tr>
<th>Player</th>
<th>Position</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
</tr>
<tr>
<td>Matt Ryan</td>
<td>QB</td>
<td id="01">11</td>
<td id="02">15</td>
<td id="03">00</td>
<td id="04">14</td>
<td id="05">14</td>
</tr>
<tr>
<td>Marshawn Lynch</td>
<td>RB</td>
<td id="11">06</td>
<td id="12">01</td>
<td id="13">09</td>
<td id="14">40</td>
<td id="15">12</td>
</tr>
<tr>
<td>Calvin Johsnon</td>
<td>WR</td>
<td id="21">00</td>
<td id="22">00</td>
<td id="23">00</td>
<td id="24">00</td>
<td id="25">00</td>
</tr>
<tr>
<td>Allen Hurns</td>
<td>WR</td>
<td id="31">00</td>
<td id="32">04</td>
<td id="33">23</td>
<td id="34">17</td>
<td id="35">05</td>
</tr>
<tr>
<td>A.J. Green</td>
<td>WR</td>
<td id="41">00</td>
<td id="42">00</td>
<td id="43">10</td>
<td id="44">02</td>
<td id="45">18</td>
</tr>
<tr>
<td>Julius Thomas</td>
<td>Tight End</td>
<td id="51">02</td>
<td id="52">02</td>
<td id="53">09</td>
<td id="54">18</td>
<td id="55">00</td>
</tr>
<tr>
<td>Matt Bryant</td>
<td>Kicker</td>
<td id="61">00</td>
<td id="62">03</td>
<td id="63">00</td>
<td id="64">15</td>
<td id="65">15</td>
</tr>
<tr>
<td>Texans</td>
<td>Defense</td>
<td id="71">04</td>
<td id="72">07</td>
<td id="73">12</td>
<td id="74">00</td>
<td id="75">08</td>
</tr>
<tr>
<td>Total:</td>
<td></td>
<td id="total1">00</td>
<td id="total2">00</td>
<td id="total3">00</td>
<td id="total4">00</td>
<td id="total5">00</td>
</tr>
</table>
<p>Total: <span id="totalAll"></span>
</p>
</body>
</html>
Recently, I was charged with creating a fantasy football website for my group of friends, having minimal Javascript and HTML experience. I don't mind manually inputing data from the NFL website, but I thought it would be cool to have a script to automatically add up the numbers in the table. But, the code I wrote doesn't work. Nobody I know has any knowledge in Computer Science, and Ive turned to Google throughout the whole process. The browser console returns no errors. What I expect to happen is the total points from all of my tds for each week go into the week total at the bottom, and then the week totals be added up into the final total. What really happens is nothing. Half the time, when I change something, the page crashes.
I cant seem to get a JSfiddle to run without crashing on run-time, so im putting it into pastebin
http://pastebin.com/Wb3ENMZY
All the for loops at the end are temporary, to be taken down when the first part works.
Not too sure why your code wouldn't work in JSFiddle
Here's a fiddle with a work example of what you were trying to accomplish Demo
HTML
<table>
<thead>
<tr>
<th>Player</th>
<th>Position</th>
<th>Week 7</th>
<th>Week 8</th>
<th>Week 9</th>
<th>Week 10</th>
<th>Week 11</th>
</tr>
<thead>
<tbody>
<tr>
<td>Matt Ryan</td>
<td>QB</td>
<td id="01">11</td>
<td id="02">15</td>
<td id="03">00</td>
<td id="04">14</td>
<td id="05">14</td>
</tr>
<tr>
<td>Marshawn Lynch</td>
<td>RB</td>
<td id="11">06</td>
<td id="12">01</td>
<td id="13">09</td>
<td id="14">40</td>
<td id="15">12</td>
</tr>
<tr>
<td>Calvin Johsnon</td>
<td>WR</td>
<td id="21">00</td>
<td id="22">00</td>
<td id="23">00</td>
<td id="24">00</td>
<td id="25">00</td>
</tr>
<tr>
<td>Allen Hurns</td>
<td>WR</td>
<td id="31">00</td>
<td id="32">04</td>
<td id="33">23</td>
<td id="34">17</td>
<td id="35">05</td>
</tr>
<tr>
<td>A.J. Green</td>
<td>WR</td>
<td id="41">00</td>
<td id="42">00</td>
<td id="43">10</td>
<td id="44">02</td>
<td id="45">18</td>
</tr>
<tr>
<td>Julius Thomas</td>
<td>Tight End</td>
<td id="51">02</td>
<td id="52">02</td>
<td id="53">09</td>
<td id="54">18</td>
<td id="55">00</td>
</tr>
<tr>
<td>Matt Bryant</td>
<td>Kicker</td>
<td id="61">00</td>
<td id="62">03</td>
<td id="63">00</td>
<td id="64">15</td>
<td id="65">15</td>
</tr>
<tr>
<td>Texans</td>
<td>Defense</td>
<td id="71">04</td>
<td id="72">07</td>
<td id="73">12</td>
<td id="74">00</td>
<td id="75">08</td>
</tr>
<tr>
<td>Total:</td>
<td></td>
<td id="total1">00</td>
<td id="total2">00</td>
<td id="total3">00</td>
<td id="total4">00</td>
<td id="total5">00</td>
</tr>
</tbody>
</table>
<p>Total: <span id="totalAll"></span>
</p>
Note the addition of the <thead> and the <tbody> this is so we can easily select the body rows in JQuery
Code
//Make a list of values for each column
var sums = [0,0,0,0,0];
//Go through each row in the body of the table
$("tbody tr").each(function () {
//We start at 2 because thats the firs of the weeks columns
for(var i = 2; i <= 6; i++)
{
//Add the current column's value to the sum. Note we use :eq() selector to get the i'th column
sums[i-2] += parseInt($("td:eq("+i+")", this).html());
}
});
var total = 0;
//Go through each column sum totalling it and writing it to the appropriate column
for(var i = 0; i < sums.length; i++)
{
total += sums[i];
$("#total" + (i + 1)).html(sums[i]);
}
//Write the total
$("#totalAll").html(total);
From your original code
for (p = 0; i < numbers.length; p++) {
var total1 = 0;
$.each(numbers[0], function() {
total1 += this;
});
}
This was causing Javascript to loop forever. Your for loop will loop until i < numbers.length but i isn't defined here. You probably mean p there. After replacing the i with p it no longer looped forever but each column would have the same value, numbers[0] should be changed for each column you're parsing.
I'm still having issues with your original code even after fixing those errors though.

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