"querySelectorAll" on HTML table not working as expected - javascript

I have a task to use querySelectorAll on the HTML table tr elements using nth-child to print different colors for both even and odd numbers but only the even is working. My code below
I'm also getting the error that "Uncaught TypeError: Cannot read property 'style' of undefined",
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Numbers</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 = odd</td>
</tr>
<tr>
<td>2 = even</td>
</tr>
<tr>
<td>3 = odd</td>
</tr>
<tr>
<td>4 = even</td>
</tr>
</tbody>
</table>
<button onclick='execute()'>Execute</button>
</body>
<script>
function execute() {
// your code goes here
var odd = document.querySelectorAll("tbody tr:nth-child(odd)")
var even = document.querySelectorAll("tbody tr:nth-child(even)")
for(i = 0; i<= odd.length; i++){
odd[i].style.backgroundColor = "red"
}
for(i = 0; i<= even.length; i++){
even[i].style.backgroundColor = "green"
}
}
</script>
</html>

You want i < odd.length instead of i <= odd.length (and the same change for the evens). length is going to be last index plus one because array indices are zero-based.
Overrunning the end of the array causes an error, which stops execution so you don't see any of the changes that otherwise would've followed.
Works with just those changes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Numbers</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 = odd</td>
</tr>
<tr>
<td>2 = even</td>
</tr>
<tr>
<td>3 = odd</td>
</tr>
<tr>
<td>4 = even</td>
</tr>
</tbody>
</table>
<button onclick='execute()'>Execute</button>
</body>
<script>
function execute() {
// your code goes here
var odd = document.querySelectorAll("tbody tr:nth-child(odd)")
var even = document.querySelectorAll("tbody tr:nth-child(even)")
for(i = 0; i< odd.length; i++){
odd[i].style.backgroundColor = "red"
}
for(i = 0; i< even.length; i++){
even[i].style.backgroundColor = "green"
}
}
</script>
</html>

There's a bug in the loop condition: by using <=, you tell JS to iterate from 0 to the value equal to odd.length. However, there is nothing at odd[odd.length], because its indices range from 0 to odd.length - 1, since arrays are 0-indexed. This is why you get the error that you're seeing - non-existent array elements always evaluate to undefined, whose properties cannot be referred to.
Since the first loop throws an error, JavaScript ends execution and never gets to the second loop. This is why the "even" rows aren't working.

Related

Jquery datatable how to get parent data from child

I have a jquery datatable of something like this
when i click the plus icon, it will show 2 buttons the capabilities and reimbursement, what I want is when i click the capabilities button, I want to get the parent row which are name, all and etc. Is that possible? I tried several method but it doesn't work.
What I tried is
function set_credentials(el) {
var tr = $(el).closest('tr').parents('tr');
var prevtr = tr.prev('tr')[0];
console.log(prevtr)
But i get the html dom.
I think I almost got it but i need some help. Thanks
Is this what you want? I console.log(name) for the result.
Example below
$("#example").on("click", set_credentials);
function set_credentials(event) {
if (event.target.tagName === "BUTTON") {
var tr = $(event.target).closest("tr");
var prevtr = tr.prev();
var name = prevtr.find("td.mws_name").text();
console.log(name);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<div>
<table id="example">
<thead>
<th>name</th>
<th>date</th>
<th>button</th>
</thead>
<tbody>
<tr>
<td class="mws_name">joe</td>
<td>2011-1-1</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button>set</button></td>
</tr>
<tr>
<td class="mws_name">Sam</td>
<td>2011-5-1</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button>set</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

How to properly access an array's elements within a for loop?

I am currently trying to take an ArrayList that I recieved as a response from a servlet, and print it as a table. The array currently has 2 objects within it. Calling on those objects and their elements works just fine, ie.
theArray[1].amount
works just fine, returning the "amount" value within the first object in the array.
But when I try to use theArray[i].amount in a for loop, I'm being told "theArray[i] is undefined"?
Help please!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Reimbursements</title>
</head>
<body>
<table id="myTable" style="border: solid 1px black; background-color: bisque;">
<thead>
<tr>
<th width="100">Reimbursement ID</th>
<th width="100">Amount in $</th>
<th width="100">Time Submitted</th>
<th width="100">Time Resolved</th>
<th width="100">Description</th>
<th width="100">Reimbursement Author</th>
<th width="100">Reimbursement Resolver</th>
<th width="100">Status ID</th>
<th width="100">Type ID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var table = document.getElementById('myTable');
var theArray = JSON.parse(sessionStorage.getItem('reimbArray'));
var length = theArray.length;
var i=1;
console.log(theArray[1].amount);
for(i=1; i <= length; i++) {
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
cell1.innerHTML = theArray[i].reimbId;
var cell2 = row.insertCell(1);
cell2.innerHTML = theArray[i].amount;
}
</script>
<script src="scripts/index.js"></script>
</body>
</html>
In code we start counting from 0, so your loop needs some adjustments. You are doing:
for(i=1; i <= length; i++)
so the index will go 1, 2 for an array of length 2. But you want to go 0, 1.
So either start from 0 with for(i=0; i < length; i++), or substract the offset in your array access: theArray[i - 1].amount;
Did you tried to use the forEach() function for Javascript?
It may help you.

Calculate the sum of input values in the last column of table in javascript

Tying to sum up the dynamic input values in the last column of my table. If I hard code the number values then the calculation works just fine. If I input the values my self using a I get NaN
Ive used
My html table is added upon load and the rows are added as needed via a button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table id='table' border="1">
<tr>
<th>RO#</th>
<th>Work</th>
<th>Time</th>
</tr>
<tr>
<td>615235</td>
<td>lof, rotate</td>
<!-- <td>23</td> -->
<td><input type="number" /></td>
</tr>
<tr>
<td>6154879</td>
<td>engine, trans</td>
<!-- <td>23</td> -->
<td><input typ="number" /></td>
</tr>
<tr>
<td>6158978</td>
<td>rotate, serp belt, timing belt</td>
<!-- <td>23</td> -->
<td><input type="number" /></td>
</tr>
</table>
<br>
<button onclick='calculate()'>Calculate</button>
<script>
function calculate() {
let tbl = document.getElementById('table'),
sumVal = 0;
for (let i = 1; i < tbl.rows.length; i++) {
sumVal = sumVal + parseInt(tbl.rows[i].cells[2].input);
}
console.log(sumVal);
}
</script>
</body>
</html>
I get NaN when using the <td><input type="number or type="text"><td> code
The problem is that the input property does not exist in tbl.rows[i].cells[2]. Honestly, I don't know if it's possible to get the input values from Table cells Collection that you're trying to utilize.
I suggest this approach, using querySelectorAll in which we specify the inputs we'd like to get data from:
function calculate() {
let tbl = document.querySelectorAll("table input[type='number']"),
sumVal = 0;
for (let i = 0; i < tbl.length; i++) {
sumVal += Number(tbl[i].value);
}
console.log(sumVal);
}

how to enter an array values in table to fill in no of rows in 1 column?

i want in table seven header are there example:numbers,assending order,decending order,max values,min values,sum of all values,avg values...
an array values i had taken random values....and it should be entered in no of rows and only in 1 column...
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Array</title>
</head>
<body>
<table id="table" border="2" style="border:12px solid brown">
<tr>
<th>numbers</th>
<th>assending order</th>
<th>decenting order</th>
<th>max value</th>
<th>minimum value</th>
</tr>
<tr >
<td></td>
</tr>
<p id="all">sd</p>
</table>
<script>
var array=[["1"],["5"],["10"],["6"],["3"],["17"],["19"],["24"],["7"],["8"],["11"],
["13"],["15"],["15"],["12"],["14"],["16"],["18"],["21"],["20"]],
table=document.getElementById("table")
for(i=1;i<array.length;i++){
for(j=0;j<table.rows[i].cells[0].length;j++){
table.rows[i].cells[0].innerHTML=array[i][j];
console.log(table.rows[i].cells[0].innerHTML=array[i][j])
}
}
</script>
</body>
</html>
You need to follow these steps:
Get the reference of the table through it's id value as document.getElementById("table")
set the value of array which you want to fill in the table. Also set the number of columns value in a variable, say columns so that you can loop over each column and fill the values for each row in each column.
Create a new row table.insertRow(i+1); below each created row
Create columns for each row row.insertCell(j);
Insert the value in each column from the array cells[j].innerHTML=array[i][j];
var array=[["1"],["5"],["10"],["6"],["3"],["17"],["19"],["24"],["7"],["8"],["11"],
["13"],["15"],["15"],["12"],["14"],["16"],["18"],["21"],["20"]];
var table = document.getElementById("table");
var columns = 5;
for(i=0;i<array.length;i++){
var row = table.insertRow(i+1);
var cells = [];
for(j=0;j<columns;j++){
cells[j] = row.insertCell(j);
if(array[i][j]){
cells[j].innerHTML=array[i][j];
}
}
}
<table id="table" border="2" style="border:12px solid brown">
<tr>
<th>numbers</th>
<th>assending order</th>
<th>decenting order</th>
<th>max value</th>
<th>minimum value</th>
</tr>
<p id="all">Table</p>
</table>

Sort a table on clicking the header of each column using jQuery without duplicating the entire table

Trying to sort the table by just duplicating the row and not the entire table. On click of the column header that column's data must be compared and sorted and the rows rearranged , but I don't know where i am going wrong.Here is my code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Table Sort</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function() {
$('th').click(function() {
var ColNo = parseInt($(this).index());
var rows= $('tbody').children('tr');
var TotRows = parseInt(rows.length);
for (var i = TotRows-1; i >= 0; i--) {
for (var j = TotRows-1; j > 0; j--) {
var jint = parseInt(j);
var frstval = parseInt(rows[jint].getElementsByTagName("td")[ColNo].innerHTML);
var scndval = parseInt(rows[jint - 1].getElementsByTagName("td")[ColNo].innerHTML);
if (frstval < scndval) {
var a = frstval < scndval;
alert(a);
var sourceRow = $('tr').eq(jint);
alert(sourceRow);
var targetRow = $('tr').eq(jint-1);
targetRow.after(sourceRow.clone());
sourceRow.replaceWith(targetRow);
}
}
}
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>11</td>
<td>AAA</td>
<td>28</td>
</tr>
<tr>
<td>22</td>
<td>BBB</td>
<td>29</td>
</tr>
<tr>
<td>33</td>
<td>CCC</td>
<td>21</td>
</tr>
<tr>
<td>44</td>
<td>DDD</td>
<td>24</td>
</tr>
</tbody>
</table>
</body>
</html>
Better if you use a dhtmlXgrid... It's easier to implement, and you can create a JSON object of the entire dataset that you want to fill in the table. Then, just parse the JSON object into the dhtmlXgrid. With dhtmlXgrid, sorting, column size, column drag and drop, row drag and drop, etc., all such activities can be made automatically.

Categories