Changing value of a cell with JavaScript - javascript

I am having a problem changing the value of a cell in a HTML table. I am just messing around with JavaScript because I have never used it. Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name').innerHTML = name;
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
</body>
</html>

Your problem is two fold.
Your script tag is in the head and runs immediately. Only tags that have been processed before the script will be available to manipulate. You can fix this by moving your script tag below the <td name="Name"></td> tag or delaying the code with something like jQuery's document ready (requires jQuery).
document.getElementsByName returns a NodeList containing all the elements with the specified name. To manipulate the first element with this name, you can use document.getElementsByName("Name")[0].
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
<script>
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name')[0].innerHTML = name;
</script>
</body>
</html>

document.getElementsByName() returns a NodeList (notice that it's Elements rather than Element, so you have to specify which element you'd like to modify.
In this case, there's only one element, so you only need to access the first in the list:
document.getElementsByName("Name")[0].innerHTML = name;
var name = "Requiem";
var health = 100;
var strength = 1;
var agility = 1;
var intelligence = 1;
var gold = 50;
var Class = "Warrior";
document.getElementsByName('Name')[0].innerHTML = name;
<!DOCTYPE html>
<html>
<body>
<table id="myTable" border="1">
<tr>
<td>Name</td>
<td>Health</td>
<td>Strength</td>
<td>Agility</td>
<td>Intelligence</td>
<td>Gold</td>
<td>Class</td>
</tr>
<tr>
<td name="Name"></td>
<td name="Health"></td>
<td name="Strength"></td>
<td name="Agility"></td>
<td name="Intelligence"></td>
<td name="Gold"></td>
<td name="Class"></td>
</tr>
</table>
</body>
</html>

Related

For each loop to retrieve multiple messages in page

For a Chrome plugin, I need to retrieve messages. These messages are supplied to me through an html variable.
There are 2 messages in the example provided below and they both start with: <tr bgcolor="#FFFFFF"> and end with: </tr>
I retrieved the first message data, but now I need to make it so that it retrieves all the data from each of those <tr bgcolor="#FFFFFF"> </tr> messages.
What I get provided:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" type="text/css" href="xxx">
<title>Untitled</title>
</head>
<body class="bodySinScrollHor">
<table width="95%" align="center">
<tr>
<td class="etiquetaIzquierda" colspan=6>
<a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a>
</td>
</td>
</tr>
<tr>
<td colspan=6>
<hr size=1 width="100%">
</td>
</tr>
<tr id="comunicaciones">
<td colspan=6>
<table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:22</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> -->
</tr>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:21</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> -->
</tr>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Below is the code I run to retrieve the data from the first message. Note that there are 2 messages in this case, but there are people that have 54 messages so it needs to loop that many times. This part of the code:
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
Is what provides that number for me.
matches[0].forEach(function(match, index) {
var cleintcode = /<div\s*class="t_seg_codCliente">(.*?)<\/div>/.exec(match)[1];
var cleintname = /<div\s*class="t_seg_nomCliente">(.*?)<\/div>/.exec(match)[1];
var taxId = /<div\s*class="t_seg_nifCliente">(.*?)<\/div>/.exec(match)[1];
var date = /<div\s*class="t_seg_fechaPresCliente">(.*?)<\/div>/.exec(match)[1];
var state = /<div\s*class="t_seg_estadoCliente">(.*?)<\/div>/.exec(match)[1];
var expirydate = /<div\s*class="t_seg_fechaCadCliente">(.*?)<\/div>/.exec(match)[1];
var communications = /<div\s*class="t_seg_comCliente"><a .*;">(.*?)<\/a>/.exec(match)[1];
var comclient = /<div\s*class="t_seg_comCliente"><a href="javaScript:popupComs\('(.*?)'/.exec(match)[1];
var messages = "xxx" + comclient;
var html1 = httpGet(messages);
//console.log(html1);
const cleanupDocString = html1.replace(/(?:<!--|-->)/gm, '');
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString, "text/html");
//console.log(htmlDoc);
var communicationsvalue = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
if (communicationsvalue.indexOf('No existen comunicaciones asociadas a este cliente.') !== -1) {
console.log("This chat does not contain any communiction!");
} else {
//Get count of regex matches. (amount of messages)
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
var comDate = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
var comTime = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[1].textContent;
var comType = htmlDoc.getElementsByTagName('img')[1].src;
var comClient = htmlDoc.getElementsByTagName('a')[1].textContent;
var comSubject = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[6].textContent;
const element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[7];
var pulledMessage = element.innerHTML;
var messageData = [{
clientCode: cleintcode,
clientName: cleintname,
taxID: taxId,
cleintDate: date,
cleintState: state,
cleintExpirydate: expirydate
},
{
mesDate: comDate,
mesTime: comTime,
mesType: comType,
mesClient: comClient,
mesSubject: comSubject,
mesText: pulledMessage
}
];
console.log(messageData);
}
});
The code above gives me this console log:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
Note that array 0 should not change because these messages are from the same person. I just need to grab the second message as well. So I technically need a second array like array 1 containing the data from the second message.
Wanted result:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
3. 3:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
I know I have to build a for loop, but I have no idea on how do this, so it looks for the second <tr bgcolor="#FFFFFF"> </tr> after the first.
Content is slightly edited to hide personal information.
You may possibly do as follows;
var data = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="STYLESHEET" type="text/css" href="xxx"> <title>Untitled</title> </head> <body class="bodySinScrollHor"> <table width="95%" align="center"> <tr> <td class="etiquetaIzquierda" colspan=6> <a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a> </td> </td> </tr> <tr> <td colspan=6> <hr size=1 width="100%"> </td> </tr> <tr id="comunicaciones"> <td colspan=6> <table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:22</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> --> </tr> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:21</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> --> </tr> </td> </tr> </table> </td> </tr> </table> </body> </html>';
var adiv = document.createElement("div"),
msgs = [],
trs;
adiv.innerHTML = data;
trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
trs.forEach(function(tr){
var d = [];
tr.querySelectorAll("td")
.forEach(function(td){
var img = td.querySelector("img"),
src = img && img.attributes.getNamedItem("src").value;
d.push(src || td.textContent);
});
msgs.push(d);
});
console.log(msgs);
Are you looking for this?
var trs = $('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs.eq(i).find("td").eq(0).text();
//other properties like this
currentOutput.cleintExpirydate=trs.eq(i).find("td").eq(1).text();
//add all your required properties
output.push(currentOutput);
}
console.log(output)
Without jquery
var trs = document.querySelectorAll('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs[i].getElementsByTagName('td')[0].innerText;
//other properties like this
currentOutput.cleintExpirydate=trs[i].getElementsByTagName('td')[0].innerText;
//add all your required properties
output.push(currentOutput);
}
console.log(output)

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.

Can't seem to use element IDs generated dynamically

I want to create a tiered pay calculator utility.
In my Javascript file I dynamically add rows and fields to a table I created with the HTML from a list of names I have in a text input field. The rows consist of a name label column, a text input column to put they're gross earnings in and a calculated pay output column.
I would like for it to update the calculated pay column automatically when I make a change in the text input in the gross earnings column. Although I can trace the element ids through to the calculatePay function I can't seem to use or set their properties. I get the feeling they are not unique as well. Any ideas?
BTW you have to click the update button right now to run the Javascript.
Edit - made some changes per suggestion. Still can't seem to take variables passed to the calculatePay function and simply turn them around and spit them back out into the Pay column of my table.
Edit - SOLVED. The issue was closure, which I didn't understand at first but here's the skinny. To isolate the scope of the variables so they don't get re-wrote every time the loop comes around they need to be declared inside a function that gets recreated with every loop iteration (because Javascript scopes to the function instead of to the code block). Things to note - this does not work if you just declare a nameless function in the middle of your loop. You must return it to a variable(i.e. var buildElement = function(){Yada Yada}();). Also, after the function add () to execute it.
Javascript
function buildTable(){
var artists = document.getElementById("artlist").value;
var names = artists.split(",");
var len = names.length;
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
for (i=0 ; i < len; i++){
var buildElement = function(){
var row = ptable.insertRow(rowLength);
var nameCell = row.insertCell(0);
var grossCell = row.insertCell(1);
var payCell = row.insertCell(2);
var grossText = document.createElement("input");
grossText.type = "type";
grossText.name = "gtext[]";
grossText.id = "gross" + names[i];
payCell.id = "pay" + names[i];
grossText.onchange = function(){calculatePay(payCell.id, grossText.id);};
grossCell.appendChild(grossText);
nameCell.innerHTML = names[i];
}();
}
}
function resetTable(){
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
if (rowLength>2){
for (p=rowLength; p>2; p--){
ptable.deleteRow(2);
}
}
buildTable();
}
function calculatePay(target, gross) {
document.getElementById(target).innerHTML = document.getElementById(gross).value;
}
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<div>
<table id="payTable">
<tr>
<th colspan=3 class="hdr">
Calculator
</th>
</tr>
<tr>
<th class="hdr">
Name
</th>
<th class="hdr">
Gross
</th>
<th class="hdr">
Pay
</th>
</tr>
</table>
</div>
<div>
<table>
<tr>
<th colspan=3 class="hdr">
SETTINGS
</th>
</tr>
<tr>
<th colspan=3 class="hdr">
Breakpoints
</th>
</tr>
<tr>
<td>Break 1 at $
<input type="text" name="break1" id="break1" value="300"/>
</td>
<td>
</td>
<td>Break 2 at $
<input type="text" name="break2" id="break2" value="900"/>
</td>
</tr>
<tr>
<th colspan=3 class="hdr">
Percentage levels
</th>
</tr>
<tr>
<td>
Below break 1:
<input type="text" size="4" name="per1" id="per1" value="50"/>%
</td>
<td>
Between breaks 1 and 2:
<input type="text" size="4" name="per2" id="per2" value="60"/>%
</td>
<td>
Over break 2:
<input type="text" size="4" name="per3" id="per3" value="70"/>%
</td>
</tr>
<tr>
<td>
Artists:
<input type="text" name="artlist" id="artlist" value="Brian,Eric,Christie,Cynthia,Shawn"/>
</td>
<td>
</td>
<td class="hdr">
<button onclick="resetTable()">Update</button>
</td>
</tr>
</div>
</body>
</html>
The issue was closure, which I didn't understand at first but here's the skinny. To isolate the scope of the variables so they don't get re-wrote every time the loop comes around they need to be declared inside a function that gets recreated with every loop iteration (because javascript scopes to the function instead of to the code block). Things to note - this does not work if you just declare a nameless function in the middle of your loop. You must return it to a variable(i.e. "var buildElement = function(){Yada Yada}();"). Also, after the function add () to execute it.
Javascript
function buildTable(){
var artists = document.getElementById("artlist").value;
var names = artists.split(",");
var len = names.length;
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
for (i=0 ; i < len; i++){
var buildElement = function(){
var row = ptable.insertRow(rowLength);
var nameCell = row.insertCell(0);
var grossCell = row.insertCell(1);
var payCell = row.insertCell(2);
var grossText = document.createElement("input");
grossText.type = "type";
grossText.name = "gtext[]";
grossText.id = "gross" + names[i];
payCell.id = "pay" + names[i];
grossText.onchange = function(){calculatePay(payCell.id, grossText.id);};
grossCell.appendChild(grossText);
nameCell.innerHTML = names[i];
}();
}
}
function resetTable(){
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
if (rowLength>2){
for (p=rowLength; p>2; p--){
ptable.deleteRow(2);
}
}
buildTable();
}
function calculatePay(target, gross) {
document.getElementById(target).innerHTML = document.getElementById(gross).value;
}
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<div>
<table id="payTable">
<tr>
<th colspan=3 class="hdr">
Calculator
</th>
</tr>
<tr>
<th class="hdr">
Name
</th>
<th class="hdr">
Gross
</th>
<th class="hdr">
Pay
</th>
</tr>
</table>
</div>
<div>
<table>
<tr>
<th colspan=3 class="hdr">
SETTINGS
</th>
</tr>
<tr>
<th colspan=3 class="hdr">
Breakpoints
</th>
</tr>
<tr>
<td>Break 1 at $
<input type="text" name="break1" id="break1" value="300"/>
</td>
<td>
</td>
<td>Break 2 at $
<input type="text" name="break2" id="break2" value="900"/>
</td>
</tr>
<tr>
<th colspan=3 class="hdr">
Percentage levels
</th>
</tr>
<tr>
<td>
Below break 1:
<input type="text" size="4" name="per1" id="per1" value="50"/>%
</td>
<td>
Between breaks 1 and 2:
<input type="text" size="4" name="per2" id="per2" value="60"/>%
</td>
<td>
Over break 2:
<input type="text" size="4" name="per3" id="per3" value="70"/>%
</td>
</tr>
<tr>
<td>
Artists:
<input type="text" name="artlist" id="artlist" value="Brian,Eric,Christie,Cynthia,Shawn"/>
</td>
<td>
</td>
<td class="hdr">
<button onclick="resetTable()">Update</button>
</td>
</tr>
</div>
</body>
</html>

Copy single value into multiple columns using JAVASCRIPT

I have this code here. I need to place the value entered by the user (say integer 10), compute an operation on it and enter the answer into the row defined by my table.
I am not able to copy the same value in the 4 columns. How should I change my code?
<html>
<table>
<tr>
<td class="demo"></td>
<td class="demo"></td>
<td class="demo"></td>
<td class="demo"></td>
</tr>
</table>
Enter Input:<input type="text" name="test"/>
<script>
function testfunc()
{
var tt=document.getElementsByName("test")[0].value;
document.getElementsByClassName("demo").innerHTML = tt*20;
}
</script>
<button onclick="testfunc()">TEST</button>
</html>
getElementsByClassName gives you a list of elements and there is no method or property on that list to manipulate all the elements in it. To manipulate the elements you'll have to iterate through the elements individually.
cells = document.getElementsByClassName("demo");
for (var i = 0; i < cells.length; i++){
cells[i].innerHTML = tt*20;
}
http://jsfiddle.net/BzmBX/
Try this function:
function testfunc(){
var tt=document.getElementsByName("test")[0].value;
var tds = document.querySelectorAll('td.demo');
var nrtds = tds.length;
for(var i=0; i<nrtds; i++) {
tds[i].innerHTML = tt;
}
}
You can also use, id's instead of classes.
Try
<html>
<head>
<script type="text/javascript">
function testfunc()
{
var tt=document.getElementById("test").value;
//alert(tt);
var log;
log = tt*20;
for(i=1;i<=4;i++)
document.getElementById("c"+i).innerHTML = log;
}
</script>
</head>
<body>
<table border=1>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
<tr>
<td id='c1'> </td>
<td id='c2'> </td>
<td id='c3'> </td>
<td id='c4'> </td>
</tr>
</table>
Enter Input: <input type="text" id="test" name="test"/>
<button onclick="Javascript:testfunc();">TEST</button>
</body>
</html>
You're almost there, only problem with the code is that the Javascript function getElementsByClassName returns a set of elements which have all the given class names.
So the correct Javascript code would be:
<script>
function testfunc() {
var tt = document.getElementsByName("test")[0].value;
// Loop through all demo table columns returned.
demoColumns = document.getElementsByClassName("demo");
for (var i = demoColumns.length - 1; i >= 0; i--) {
demoColumns[i].innerHTML = tt * 20;
};
// Incorrect.
// document.getElementsByClassName("demo").innerHTML = tt*20;
}
</script>
In your example you were trying to set the inner HTML on a collection as opposed to a single DOM element.
You might probably want to restrict to changing the contents of the table only. So adding a id "demoTbl" for the table, and using document.getElementById("demoTbl").getElementsByClassName("demo") will only search for element with class "demo" in the table id="demoTbl"
<html>
<table id="demoTbl">
<tr>
<td class="demo"></td>
<td class="demo"></td>
<td class="demo"></td>
<td class="demo"></td>
</tr>
</table>
Enter Input:<input type="text" name="test"/>
<script>
function testfunc()
{
var tt=document.getElementsByName("test")[0].value;
var sel = document.getElementById("demoTbl").getElementsByClassName("demo");
for (var i=0; i<sel.length; i++) {
sel[i].innerHTML = tt*20;
}
}
</script>
<button name="test" onclick="testfunc()">TEST</button>
</html>

How to use a JavaScript variable in a table layout?

This is my code:
<html>
<script type="text/javascript">
var data1 = "$100";
var data2 = "$80";
</script>
<body>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
</body>
</html>
I need to replace this $100 & $80 with JavaScript variable data1 & data2
How to do that?
If you assign ids to the cells you want
<td id="data1">$100</td>
<td id="data2">$80</td>
You can set their value in Javascript like this
document.getElementById("data1").innerHTML = data1;
document.getElementById("data2").innerHTML = data2;
You can see this in action on jsFiddle.
If I understood you right, and you want to replace between 100$ and 80$:
var data1 = "$100";
var data2 = "$80";
var elements = document.getElementsByTagName('td');
for (var i = 0; i < elements.length; i++) {
console.log(elements[i]);
if (elements[i].innerHTML == data1)
elements[i].innerHTML = data2;
else if (elements[i].innerHTML == data2)
elements[i].innerHTML = data1;
}​
LIVE DEMO
<html>
<script type="text/javascript">
var data1 = "$100";
var data2 = "$80";
</script>
<body>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td onload="this.textContent=data1;"></td>
</tr>
<tr>
<td>February</td>
<td onload="this.textContent=data2;"></td>
</tr>
</table>
</body>
</html>
HTML5 has no explicit databinding options, but has data- tags to insert metadata to DOM elements. More info
If you still need a more responsive way to bind your data you can try this post

Categories