What's wrong with this simple HTML table accessing? - javascript

I'm using JavaScript to access the HTML table element.
<html>
<head>
<title>Popup page</title>
</head>
<body>
<form name="F1" method="POST">
TOTAL : <p id="total"></p>
PERCENTAGE : <p id="percentage"></p>
</form>
//This table has 9 rows and 7 columns.
// I'd like to get the 6th column elements from 2nd row onwards.
<table class="collapse" >
<tbody>
<tr><td>S.No.</td><td>Subject Code</td><td>Subject Name </td><td>Int. Marks</td>
<td>Ext. Marks</td><td>Total</td><td>Credits</td><td>Result</td></tr>
<tr><td>1</td><td>GR11A1009</td><td>Environmental Science</td><td>23</td><td>66</td>
<td>89</td><td>3</td><td>P</td></tr>
<tr><td>2</td><td>GR11A1010</td><td>Mathematics - II</td><td>22</td><td>58</td>
<td>4</td><td>P</td></tr><td>80</td>
<tr><td>3</td><td>GR11A1011</td><td>Engineering Chemistry</td><td>17</td><td>53</td>
<td>70</td><td>3</td><td>P</td></tr>
<tr><td>4</td><td>GR11A1012</td><td>Engineering Graphics</td><td>20</td><td>47</td>
<td>67</td><td>3</td><td>P</td></tr>
<tr><td>5</td><td>GR11A1013</td><td>IT Workshop</td><td>25</td><td>43</td><td>68</td>
<td>2</td><td>P</td></tr>
<tr><td>6</td><td>GR11A1014</td><td>Engineering Chemistry Lab</td><td>13</td>
<td>30</td><td>43</td><td>3</td><td>P</td></tr>
<tr><td>7</td><td>GR11A1015</td><td>English Lab</td><td>20</td><td>44</td><td>64</td>
<td>3</td><td>P</td></tr>
<tr><td>8</td><td>GR11A1018</td><td>Mathematics - III</td><td>20</td><td>67</td>
<td>3</td><td>P</td></tr>
</tbody>
</table>
//JavaScript starts here
<script>
var table = document.getElementByClass("collapse");
var marks = new Array();
var total = 0,percentage;
//here is code to get all the 6th column elements fro 2nd row onwards.
for(var i=0;i<8;i++)
marks[i] = table.ChildNodes[0].ChildNodes[i+1].ChildNodes[5].nodeValue;
//here I'm adding all the values stored ( subject marks) and finding the grand total
for(var i=0;i<8;i++)
total +=marks[i];
//now, I'm calculating the percentage
percentage = total/725;
//Below code isn't having any effect. Why is it?
document.getElementById("total").innerHTML = total;
document.getElementById("percentage").innerHTML = percentage;
</script>
</body>
</html>
What is the problem with the above code ? What can I do to solve it?
Here is the output:

There are several problems with the code. In addition to the problem with getElementByClass (there is no such method, use document.getElementsByClassName("collapse")[0] instead), you are trying to access the elements in the table using ChildNodes (undefined). You probably meant to write childNodes, but you should really using children, since you don’t want to have to do with all the text nodes containing just whitespace. And you are accessing cells without checking that they exist; not all rows have 6th cell in your table.
There is also a spurious </tr> tag that confuses table parsing. Remove it.
Morever, to get the content of a td element, you cannot use nodeValue, which is defined for text nodes only. You could use innerText, but due to issues in browser support, the good old innerHTML is safer. Then you need to convert the data from string to number (otherwise adding 2 and 2 gives your 22, not 4), e.g. with the Number function. You may wish to add some error-checking here (and elsewhere).
for(var i=0;i<8;i++)
marks[i] = table.children[0].children[i+1].children[5].innerHTML;
for(var i=0;i<8;i++)
total += Number(marks[i]);

I think you mean document.getElementsByClassName()
change your document.getElementByClass to document.getElementsByClassName()
And my personal suggestion for you is to use jquery for this , which may be much more efficient and easy for this purpose
In jquery you can simplify it like this
(Dont forget to add a class to your total TD)
var total = 0;
var percentage = 0;
$(".collapse tr").each(function(e){
var tr = $(this);
var mark =$(this).find(".total").html();
var marktst=0;
if(!isNaN(Number(mark))) //NullChecking
{
marktst =Number(mark);
}
total +=marktst;
});
document.getElementById("total").innerHTML = total;
A fiddle is given below
http://jsfiddle.net/AmarnathRShenoy/j4hVc/5/

Related

Issue with getting a keyup function to get sum of input field values using plain Javascript

I'm working on a personal project and I've run into an issue that I haven't been able to solve.
Here is a function that generates new table rows into a table (with id of "tableData") when a button is clicked:
function addNewRow(){
var tableEl = document.getElementById("tableData");
var newLine = '<tr class="newEntry">';
var classArray = ["classA", "classB", "classC", "classD"];
for (var i = 0; i < classArray.length; i++){
newLine += '<td><input class="' + classArray[i] + '"></td>';
}
newLine += '</tr>';
tableEl.insertAdjacentHTML("beforeend", newLine);
}
document.getElementById("addRow").addEventListener("click", addNewRow, false);
//the element with id="addRow" is a button
I've simplified the code for the above function for the sake of readability as it's not the focus of the problem. When the button is clicked, a new row is added successfully.
The problematic part involves another function that takes the sum of the respective classes of each row and displays them in a div.
The goal is to get the sum of the values of all input fields with matching class names. For example, let's say I use the addNewRow function to get six rows. Then I want to have the div showing the sum of the values of all input fields with the class name of "classA"; the number in that div should be the sum of those six values, which gets updated as I type in the values or change the existing values in any of the input fields with class name of "ClassA".
function sumValues(divId, inputClass){
var sumVal = document.getElementsByClassName(inputClass);
var addedUp = 0;
for (var j = 0; j < sumVal.length; j++){
addedUp += Number(sumVal[j].value);
}
document.getElementById(divId).innerHTML = addedUp;
}
Here are a couple (out of several) failed attempts:
document.input.addEventListener("keyup", sumValues("genericDivId", "classA"), false);
document.getElementsByClassName("classA").onkeyup = function(){sumValues("genericDivId", "classA");}
Unfortunately, after scouring the web for a solution and failing to find one, I just added an event listener to a button that, when clicked, would update the div to show the sum of values. Also had to modify the sumValues function to take values from an array rather than accepting arguments.
My question is: How can I modify the code so that the sum value updates as I type in new values or change existing values using pure Javascript (vanilla JS)?
You are very close, document.getElementsByClassName() returns an array of DOM objects, you need to set the onkeyup function for each and every element by looping through that array.
var classA = document.getElementsByClassName('classA'); // this is an array
classA.forEach(function(elem){ // loop through the array
elem.onkeyup = function(){ // elem is a single element
sumValues("genericDivId", "classA");
}
}
Hopefully this fixes your issue
Maybe the example below is not same with your situation, but you'll get the logic, easily. Anyway, do not hesitate to ask for more guide.
document.getElementById("row_adder").addEventListener("click", function() {
var t = document.getElementById("my_table");
var r = t.insertRow(-1); // adds rows to bottom - change it to 0 for top
var c = r.insertCell(0);
c.innerHTML = "<input class='not_important_with_that_way' type='number' value='0' onchange='calculate_sum()'></input>";
});
function calculate_sum() {
var sum = ([].slice.call(document.querySelectorAll("[type=number]"))).map(e=>parseFloat(e.value)).reduce((a, b) => a+b);
document.getElementById("sum").innerHTML = sum;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<p>
<strong>Sum</strong>:<span id="sum">0</span>
</p>
</div>
<button id="row_adder">
Click me
</button>
<table id="my_table">
</table>
</body>
</html>

Capturing a class inside a table tag and capturing multiple items

So let's say I have multiple items with multiple quantities. I want to get that quantity with a variable and then print the quantities with a sentence. I know there are some syntax problems here but I am trying to give a general idea. It also doesn't have to be .write as long as it creates a sentence.
<td class="v1_shop_cart_articles_col_qty">
2
</td>
<td class="v1_shop_cart_articles_col_qty">
5
</td>
<script>
var qty = document.getElementsByClassName('v1_shop_cart_articles_col_qty');
for(var i=0; i<qty.length; i++) {
document.write(' A order was placed with a quantity of'+qty[i]+'.');
}
</script>
You're close. You can get the contents of each element with innerHTML, and convert it to an integer with parseInt(), e.g.:
for(var i=0; i<qty.length; i++) {
document.write('An order was placed with a quantity of ' +
parseInt(qty[i].innerHTML, 10) +
'.');
}
Example: http://codepen.io/paulroub/pen/BirIo

Javascript - How do you set the value of a button with an element from an array?

<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);

Can I iterate over different data- tags in a tag in a particular order?

In my HTML I have the following code. Depending on what's being shown it can
have 0,1,2,3,4 or 5 different time points. The first time period of interest is data-t0
and then next is data-t1 minus data-t0 etc.
<table id="dataTable" data-t2="1828" data-t1="1552" data-t0="1163" ></table>
<h1>Grid data</h1>
Is there a way that I can add the times to the h1 tag like this if there at least exists a
timing point data-t0?
<h1 title="Response time: t1=1163, t2=11, t3=276">Grid data</h1>
The problem I have is that I need some way for it to go through and add in the times
for each of the timing points. I can do simple jQuery but I don't know how to make it
iterate over each of the timing points.
You might just want to store your data in a single attribute using a JSON literal:
<table id="dataTable" data-t="[1163, 1552, 1828]" ></table>
var data = $("#dataTable").data('t'); //jQuery does the JSON parsing for us
var diffs = [];
for(var i = 0; i + 1 < data.length; i++) {
diffs[i] = data[i + 1] - data[i];
}
alert(diffs.join(', '));

question regarding javascript;Html generation and search current webpage for tags

Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.

Categories