how to attempt null.value in document.getelementById - javascript

I have a table where it has dynamic rows and I need to get the data and make calculations on it so I get the total number of rows in Javascript and run a loop in it. my table looks like this
<table id='mytable1'>
<tr>
<td id="name_1">Precious Metals</td>
<td id="price_1">500</td>
<td id="qty_1">10</td>
</tr>
<tr>
<td id="name_2">Non Precious Metals</td>
<td id="price_2">200</td>
<td id="qty_2">5</td>
</tr>
<tr>
<td id="name_3">Gemstones</td>
<td id="price_3">300</td>
<td id="qty_3">10</td>
</tr>
and my javascript looks like this
<script>
var counter = $('#mytable1 tr').length;
for (i = 1; i <= counter; i++) {
var price = document.getElementById('price_'+i).value;
var qty= document.getElementById('qty'+i).value;
var price_calc = price * qty;
var total_price = total_price + price_calc;
}
</script>
The problem is that if there is one row missed, I mean Admin delete the row #2 and now there will be two rows and when the loop runs and it did not find the row#2 then it throws the error. Please help me or guide me about how should I go with this problem

You can simplify your HTML and make the calculations independent of the number of rows you have in the table. On top of that, jQuery is not necessary.
Documentation in the source.
const table = document.getElementById("mytable1");
// Put all existing rows inside the table in an array
const rows = [...table.getElementsByTagName("tr")];
// Loop through all rows
rows.map( row => {
// Price is in the first cell
const price = parseInt(row.cells[1].innerHTML);
// Quantity is in the second cell
const quantity = parseInt(row.cells[2].innerHTML);
// Calculate total value for each row
const total_price = price * quantity;
console.log(total_price);
});
<table id='mytable1'>
<tr>
<td>Precious Metals</td>
<td>500</td>
<td>10</td>
</tr>
<tr>
<td>Non Precious Metals</td>
<td>200</td>
<td>5</td>
</tr>
<tr>
<td>Gemstones</td>
<td>300</td>
<td>10</td>
</tr>
</table>

Related

how to select a range of html table cell value in javascript?

Please help!
I have a html table and for example I want to select the first 4 cell value of the table but I don't know how.
I tried:
var table = document.getElementById("td")
selectedCell = table.cells[0:4]
javascript does not understand this way.
You can access a cell by its row index and cell index like this:
var table = document.getElementById('table1')
for(let rowIndex = 0; rowIndex < 2; rowIndex++){
for(let cellIndex = 0; cellIndex < 2; cellIndex++){
console.log(table.rows[rowIndex].cells[cellIndex]);
}
}
<table id="table1" style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
<tr>
<td>March</td>
<td>$70</td>
</tr>
<tr>
<td>April</td>
<td>$160</td>
</tr>
</table>
if you give some sample data and an expected output I can use it to help you to make adjustment to this.

Calculate the the value of all EvenChild elements javascript / php

I have this table, that holds 3 colums , name , price and remove button.
What It needs is a way to calculate the sum of all even childs from the TR parent (every second TD since its the one that contains the price).
I am assuming Javascript will do that but im not sure how its gonna address Even or Odd elements.
I've also thought about using CSS to add some type of markers for the Even or Odd elements and use these markers to guide js but this is beyond my current knowledge.
I searched a lot for a solution to this, but to no avail..
Something along the lines of -
function count() {
var oddchildren = document.getElementByID('#order-table').childNodes.OddchildNodes;
var result = oddchildren + oddchildren;
}
I know this piece of code isnt even nearly proper, its just pseudo-code to represent the basic idea of what we need for the end result.
Here is the JS FIDDLE https://jsfiddle.net/x8usjfs6/
window.addEventListener('DOMContentLoaded', () => {
function calc() {
// get the price elements
let prices = document.querySelectorAll('.price');
// turn them into an array and add up the prices
let total = [].slice
.call(prices)
.reduce((prev, curr) => parseInt(curr.innerText) + prev, 0);
// display the total
document.querySelector('.total').innerHTML = total;
}
function remove(el) {
// keep going up the tree until you find the row
while (el.tagName !== "TR") {
el = el.parentElement;
}
// remove the row
el.remove();
}
// each time a button is clicked, remove a row and
// recalculate the total
function removeAndRecalc() {
remove(this);
calc();
}
// add click listeners to the remove buttons
[].slice
.call(document.querySelectorAll('.remove'))
.forEach(el => el.addEventListener('click', removeAndRecalc));
// calculate the total right off the bat
calc();
});
.price:before {
content: '$'
}
.total:before {
content: '$'
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<table>
<thead>
<tr>
<td>Item</td>
<td>Price</td>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<td>Engineering Suit Level I</td>
<td class="price">100</td>
<td><button class="remove">Remove</button></td>
</tr>
<tr>
<td>Engineering Suit Level I</td>
<td class="price">100</td>
<td><button class="remove">Remove</button></td>
</tr>
<tr>
<td>Standart Plasma Cutter</td>
<td class="price">120</td>
<td><button class="remove">Remove</button></td>
</tr>
<tr>
<td>Standart Plasma Cutter</td>
<td class="price">120</td>
<td><button class="remove">Remove</button></td>
</tr>
<tr>
<td>Total:</td>
<td class="total"></td>
<td></td>
</tr>
</tbody>
</table>

Need to compare a certain cell in contiguous rows and find rows where the value of that cell changes

I have an html table generated dynamically from a database. Rows where a particular cell value is the same represents paired data and I want to separate those pairs with an empty row. The best way I can think of is to find where that value differs from the preceding value. Is this possible?
<table id="myTable">
<tr>
<th>Team #</th>
<th>Name</th>
<th>Age</th>
</tr>
<tbody>
<tr class="data-in-table">
<td class="id">12345</td>
<td>Tom</td>
<td>46</td>
<tr class="data-in-table">
<td class="id">12345</td>
<td>Dick</td>
<td>32</td>
<tr class="data-in-table">
<td class="id">34567</td>
<td>Harry</td>
<td>45</td>
<tr class="data-in-table">
<td class="id">76543</td>
<td>Will</td>
<td>45</td>
</tr>
<tr class="data-in-table">
<td class="id">76543</td>
<td>Sam</td>
<td>45</td>
</tr>
</tbody>
This is code I've seen comparing adjacent cells and tried to change for my needs:
$("#myTable").each(function () {
$(this).find('tr').each(function (index) {
var currentRow = $(this);
var nextRow = $(this).next('tr').length > 0 ? $(this).next('tr') : null;
if (index%2==0&&nextRow && currentRow(td[0].text() != nextRow(td[0].text()) {
$('#myTable tr:next').after('<tr><td></td><td></td><td></td></tr>');
}
});
});
I'd like it to look something like this:
Team # Name Age
12345 Tom 46
12345 Dick 32
34567 Harry 45
76543 Will 45
76543 Sam 45
As the database updates, team members will always be positioned adjacent to each other, but sometimes one teammate will appear before the second teammate and the table should reflect that.
I found that this works, through trial and error:
var last = ''
var rowCount = $('#myTable >tbody >tr').length;
for (var i=0;i<rowCount-1;i++) {
if (last != $('#myTable tr .id:eq('+i+')').html()) {
var lastRow = $('#myTable tr .id:eq('+i+')')
$(lastRow).parents('tr').before('<tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr>')
}
var last = $('#myTable tr .id:eq('+i+')').html()
}
I don't know if there is a more efficient way than using a for.. statement to run through each row.

Search the table by cell content with jquery and relative referencing

Having such table
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> 1 </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> x </td>
<td class="TableCol3"> # </td>
</tr>
<tr class="TableEven">
<td>....</td>
</tr>
</tbody>
E.g. each cell has own class indicating it's column number TableCol0,1,2..N
In each row, needed compare the content of the cells in column 1 and 2 and write the result into colum3.
Managed the following script,
$(document).ready(function() {
var toterr = 0;
$('tbody tr.TableEven,tbody tr.TableOdd').each(function() {
var wanted = $(this).find('.TableCol1' ).html();
var actual = $(this).find('.TableCol2' ).html();
//console.log('wanted='+wanted+'=actual='+actual+'=');
if ( wanted == actual ) {
$(this).find('.TableCol3').text('ok');
} else {
$(this).find('.TableCol3').text('ERROR');
toterr++;
}
});
$('#totalerror').text(toterr);
});
It is probably not optimal, but works.
Now have a bit different scenario: Need compare two cells what are before a cell with a specified content (:CMP:), e.g:
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> x </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> :CMP: </td>
<td class="TableCol3"> etc </td>
</tr>
<tr class="TableEven">
<td class="TableCol0"> N </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> y </td>
<td class="TableCol3"> :CMP: </td>
</tr>
</tbody>
For each row, need compare cells what are before :CMP:, and replace the :CMP: with the result. e.g.
in the 1st row need compare the x and x and write ok in the cell .TableCol2
in the 2nd row need compare the x and y and write ERROR in the cell .TableCol3
I haven't idea how to modify the above script.
Can easily get the index of the cell that contains ':CMP:' and use the index to reference the previous cells. Or use traverses like prev() or use eq() once index is found.
$('tbody tr').each(function () {
var $cells = $(this).children(),
$cmp = $cells.filter(':contains(":CMP:")'),
cmpIndex = $cells.index($cmp);
// array of values of previous cells
var values = $.map($cells.slice(cmpIndex - 2, cmpIndex), function (el) {
return $.trim($(el).text());
});
// make sure we have 2 cells with values and compare
var cmpText = values.length === 2 && values[0] === values[1] ? 'OK' : 'ERROR';
$cmp.text(cmpText);
});
DEMO

How to extract text inside nested HTML using JQuery?

I have here HTML Code:
<div class="actResult" style="border: solid">
<table>
<tbody>
<tr>
<td>Order Number</td>
<td>1</td>
</tr>
<tr>
<td>Customer Number</td>
<td>3</td>
</tr>
<tr>
<td>Complaint Code</td>
<td>b</td>
</tr>
<tr>
<td>Receivable Receipt Number</td>
<td>5</td>
</tr>
<tr>
<td>Date Called</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Checkup</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Service</td>
<td>2014-03-21</td>
</tr>
<tr>
<td>Checkup Status</td>
<td>Y</td>
</tr>
<tr>
<td>Service Status</td>
<td>N</td>
</tr>
<tr>
<td>Technician Number Checkup</td>
<td>3</td>
</tr>
<tr>
<td>Technician Number Service</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
I want to get the values of the tags and put them into an array with the a structure like array("first td" => "second td"), so for this case the array would be array("Order Number" => "1", "Customer Number" => "3", "Complaint Code" => "b", ...) and so on.
After that, the final array would be sent into a PHP code.
I've been trying to extract some of the values from the HTML using var html = $(this).filter(function( index ){ return $("td", this) }).filter(":odd").text(); and various other combinations of filter(), but it doesn't seem to work for me.
How do I go about doing what I want to do?
jsFiddle Demo
You are going to want to use .each for that and iterate through the rows in the table. For each row, take the first cell (.eq(0)) as the key, and the second cell (.eq(1)) as the value. Place these in a result object.
//object to hold resulting data
var result = {};
//iterate through rows
$('.actResult tr').each(function(){
//get collection of cells
var $tds = $(this).find('td');
//set the key in result to the first cell, and the value to the second cell
result[$tds.eq(0).html()] = $tds.eq(1).text();
});
You can get the rows property of the table element and create an object based on the cells' value:
var rows = document.querySelector('.actResult table').rows,
data = {}, c, l = rows.length, i = 0;
for (; i < l; i++) {
c = rows[i].cells;
data[c[0].innerHTML] = c[1].innerHTML;
}
http://jsfiddle.net/tG8F6/

Categories