I have an HTML table fetching values dynamically from the database and I have used the sum function to calculate the sum of entire column.
These are my columns where I am fetching the sum total of a column
<td id="totalValue13" style="background-color: darkseagreen;"></td>
<td id="totalValue11" style="background-color: darkseagreen;"></td>
<td id="totalValue12" style="background-color: darkseagreen;"></td>
I want to pass the value of these <td>s into a textbox where I want to calculate these three values. I am using JavaScript to calculate it, given below is a JavaScript code for calculations:
<script type="text/javascript">
function calculate() {
var result = document.getElementById('result');
var el, i = 0, total = 0;
while (el = document.getElementById('v'+(i++))) {
el.value = el.value.replace(/\\D/, "");
total = total + Number(el.value);
}
result.value = total;
if (document.getElementById('v0').value == "" && document.getElementById('v1').value == "" && document.getElementById('v2').value == "") {
result.value = "";
}
}
</script>
I just want to know how to pass the id of an HTML table column here. Thanks.
Use .innerHTML instead of .value since table cells don't have a value. Here is an example on how to calculate the sum of given table cells with each having a separate id.
function calculate()
{
var result = document.getElementById('result');
var v1 = document.getElementById('totalValue11');
var v2 = document.getElementById('totalValue12');
var v3 = document.getElementById('totalValue13');
var el, sum = 0;
var inputList = [v1,v2,v3];
for(var i=0; i<inputList.length; i++)
{
el = inputList[i];
if(el.innerHTML != '' && !isNaN(el.innerHTML))
{
sum += parseFloat(el.innerHTML);
}
}
result.value = sum; // If needed to write to cell use result.innerHTML = sum;
}
// Call it whenever you like
calculate();
td
{
background-color: darkseagreen;
}
<table>
<tr>
<td id="totalValue13">5</td>
<td id="totalValue11">3</td>
<td id="totalValue12">25</td>
</tr>
<tr>
<td colspan="2"><label for="result">Result:</label><input type="text" id="result" value="" readonly="readonly"></td>
</tr>
</table>
Related
So pretty much I have it to were it's searching for the innerHTML of the td in question in each row....however I'm trying to grab the input name attribute from below
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
Here's what i have so far
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for (var i = 0; i < rows.length; i++) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if (fullname) {
if (v.length == 0 ||
(v.length < 3 && fullname.indexOf(v) == 0) ||
(v.length >= 3 && fullname.indexOf(v) > -1)) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
var n = document.getElementById("noresults");
if (on == 0 && n) {
n.style.display = "";
document.getElementById("qt").innerHTML = q.value;
} else {
n.style.display = "none";
}
However right now it's only indicating within the td.... How do I get the above to look for the name of the input inside of the td?
Much appreciated.
You don't need a lot of code for that. On most modern browser this works.
//For 1 value
myInput = document.querySelector('#tablename td [name="Client"]');
console.log(myInput);
//For more values
myInput2 = document.querySelectorAll('#tablename td [name="Client"]');
console.log(myInput2); //it's an array now
//Like this?
myInput3 = document.querySelector('#tablename td [name]');
if(myInput3.getAttribute('name') == 'Client'){
myInput3.setAttribute('name', 'something');
}
console.log(myInput3.parentElement);
<table id="tablename">
<tr>
<td><input name="Client"></td>
</tr>
</table>
If you have a reference to the <td> element, you can use querySelector to get a reference to the <input> (assuming it's the only or first <input> descendant) and then getAttribute to get the value of the name attribute:
// You already have a reference to the <td>
const td = document.querySelector('td');
// Get the <input>
const input = td.querySelector('input');
// Get its `name` attribute
const name = input.getAttribute('name');
console.log('name is "%s"', name);
<table>
<tbody>
<tr>
<td><input name="Client"></td>
</tr>
</tbody>
</table>
I designed a table where you can add dynamic rows, the user can select a quantity and a price for each of them. I have a series of very simple functions that allow me to delete, empty the entire table or calculate the total of all products plugged.
So far everything works fine, the problem occurs when I create 3 rows, I add it to each of their values, then I decided to delete the second row and calculate the total. As you can see, the calculation is flawed, in fact I only returns the total of the first product added to the table. I can not understand why the script does not work properly. Can anyone help me solve this problem?
<html>
<table style='width:100%' id='table'>
<tr>
<td colspan='3'><input type="button" style="background-color:#00FA9A" value="add product" onclick="add()" id="button"><input type="button" style="background-color:red" value="Delete all" onclick="deleteall()" id="button">
</td>
</tr>
<tr>
<td>Quantity</td>
<td>€</td>
<td>Delete</td>
</tr>
</table>
<input type="button" id="button" value="Calc total" onclick="total()"><input type="text" class='input' id="total">€
</html>
<script>
var idx = 0;
var cont = 0;
var buttcont = 0;
var quantity, priece;
function deleteall()
{
location.reload();
}
function add()
{
var tableRef = document.getElementById('table').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "row" + cont;
cont++;
var newCell1 = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var input1 = document.createElement('input'),
input2 = document.createElement('input');
input3 = document.createElement('button');
input1.type = 'number';
input1.style.width = "100%";
input1.id = "priece" + idx;
input1.min = 0;
input1.value = 1;
input2.type = 'text';
input2.min = 1;
input2.style.width = "100%";
input2.id = "quantity" + idx;
input3.class = 'button';
input3.innerHTML = "Delete";
if(input3.attachEvent) input3. attachEvent('onclick',function(e){deleted(e);})
else if(input3.addEventListener) input3.addEventListener('click',function(e){deleted(e);},false)
newCell1.appendChild(input1);
newCell2.appendChild(input2);
newCell3.appendChild(input3);
idx++;
}
function deleted(e)
{
if(document.removeChild && document.getElementById && document.getElementsByTagName)
{
if(!e) e = window.event;
var srg = (e.target)?e.target:e.srcElement;
while(srg.tagName != "TR"){srg = (srg.parentNode)?srg.parentNode:srg.parentElement}
var tb = document.getElementById('table').getElementsByTagName('TBODY')[0];
tb.removeChild(srg);
cont--;
idx--;
}
}
function total()
{
var total = 0;
for(var i = 0; i < idx; i++)
{
quantity = document.getElementById('quantity' + i).value;
priece = document.getElementById('priece' + i).value;
total += quantity * priece;
document.getElementById('total').value = total;
}
}
The problem comes from the fact that when you delete a row inside a table (not the last one) you have a gap in ids. getElementById will return null and your total function will raise an exception.
Add 3 products: idx is 3, ids in the DOM are 0, 1, 2;
Remove product 1: idx is 2, ids in the DOM are 0, 2; => total will throw for i == 1
Actually you can avoid looping through ids by assigning a class to your inputs. Demo.
function total()
{
var total = 0,
prices = document.querySelectorAll('.price'),
quantities = document.querySelectorAll('.quantity'),
i = 0, len = prices.length;
for(; i < len; i++) {
total += prices[i].value*quantities[i].value;
}
document.getElementById('total').value = total;
}
This is the simple app for calculating the total price of selected elements of computer hardware. It should work with innerHTML and change it dinamically.
The problem is that with my code, nothing happens, so you can check it on my fiddle or just look at the code below. It should change the price in the last box???
FIDDLE
Code:
<table style="width:230px;padding:5px;border:1px solid #f0f0f0;font-size:14px;">
<tr style="background-color:#f0f0f0;">
<th style="width:200px;text-align:left;">Elements</th>
<th align="center"></th>
</tr>
<tr style="border-bottom:1px solid #a3a3a3;">
<td>CPU unit</td>
<td align="center">✓</td>
</tr>
<tr>
<tr>
<td>Motherboard</td>
<td align="center">✓</td>
</tr>
<td>Graphic card</td>
<td align="center"><input type="checkbox" id="id_1" value="25" onchange="check();"></td>
</tr>
<tr>
<td>Memory chip</td>
<td align="center"><input type="checkbox" name="" value="" onchange="check();></td>
</tr>
<tr>
<td>Monitor</td>
<td align="center"><input type="checkbox" name="" value="" onchange="check();></td>
</tr>
</table>
<table style="width:220px;padding:1px;border:1px solid #f0f0f0;font-size:22px; font-weight:bold;">
<tr style="border-bottom:1px solid #a3a3a3;text-align:center;background-color:#80CCDC">
<td id="total"><script>document.getElementById('total').innerHTML = price;</script></td></tr><tr>
</table>
JAVASCRIPT
var basic = 300;
var add = 0;
function check()
{
if(document.getElementById("id_1").checked) {
add = 120;
}
if(document.getElementById("id_1").checked) {
add = 40;
}
if(document.getElementById("id_1").checked) {
add = 90;
}
}
var p = basic + add;
var price = p + " €";
There are a few problems
You need to call document.getElementById('total').innerHTML = price; inside check so that it updates when you click the checkbox;
You can't have multiple items with the same ID. I changed them to id_1, id_2, id_3
You need to add to the existing value in the add variable
You have to hookup change for all the checkboxes, not just the first one.
Change your code to the following http://jsfiddle.net/mendesjuan/3ja4X/3/
function check() {
var basic = 300;
var add = 0;
if(document.getElementById("id_1").checked) {
add += 120;
}
if(document.getElementById("id_2").checked) {
add += 40;
}
if(document.getElementById("id_3").checked) {
add += 90;
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
check();
For even cleaner code, you can use the following http://jsfiddle.net/mendesjuan/3ja4X/4/
function updateTotal(){
var basic = 300;
var add = 0;
var form = document.getElementById('form');
// Store the value for each item in the checkbox so
// you don't need to have three separate `if`s and IDs for them.
var checkboxes = form.getElementsByClassName('addon');
for (var i=0; i < checkboxes.length; i ++) {
if (checkboxes[i].checked) {
add += parseInt(checkboxes[i].value, 10);
}
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
// Hookup handlers from JS, not in the HTML from a single
// place using event delegation
document.getElementById('form').addEventListener('change', updateTotal);
Add your calculations inside the check function, or make it calculate after the numbers are added:
function check(){
if(document.getElementById("id_1").checked) {
add = 120;
}
if(document.getElementById("id_1").checked) {
add = 40;
}
if(document.getElementById("id_1").checked) {
add = 90;
}
var p = basic + add;
var price = p + " €";
document.getElementById('total').innerHTML = price;
}
This the code does not only run once when the page is loaded.
So I have a form that when you input a number in the Qty and Price boxes it totals them up in the Ext box as it should.
As you continue down the rows to add more Qty and price it continues to calculate the total and populates the Material Total as it should but it's not adding the tax and populating the Total box as it should be.
If you manually input an amount in the Material total box then the tax and total will automatically populate and the total is correct. I've tried using onChange, onKeyup, and even onInput but nothing seems to work.
Here is my sales tax script:
function tax(){
var material = document.getElementById( 'material' ).value;
var salestax = Math.round(((material / 100) * 8.1)*100)/100;
var total = (material*1) + (salestax * 1);
document.getElementById( 'material' ).value = material;
document.getElementById( 'salestax' ).value = salestax;
document.getElementById( 'total' ).value = total;
}
An here is the html related to the script:
<table>
<td style="width: 40px;">
<td style="width: 465px;" class="auto-style6">Material Total</td>
<td><input type="text" name="material_total"style="width: 55px"id="material"onChange="tax()"></td>
</table>
<table>
<td style="width: 40px;">
<td style="width: 465px;" class="auto-style6">Sales Tax</td>
<td><input type="text" name="sales_tax" style="width: 55px" id="salestax" onChange="tax()"></td>
</table>
<table>
<td style="width: 40px;">
<td style="width: 465px;" class="auto-style6">Shipping</td>
<td><input type="text" name="ship_cost" style="width: 55px" id="shipping"></td>
</table>
<table>
<td style="width: 40px;">
<td style="width: 465px;" class="auto-style6">Total</td>
<td><input type="text" name="total_parts_cost" style="width: 55px" id="total"></td>
</table>
Update to question: so after playing with it I found out the onpropertychange will make the form work but only in IE (I'm using IE 10) but not in firefox. I'm including the code that I use to total the Qty and Price boxes that auto populates the Ext box because that works and I use onkeyup. I don't understand why it wont work for the tax section.
enter code here function multiply1() {
var extend1 = 1;
for (var i = 1; i <= 2; i++) {
var id = "1_value" + i;
extend1 = extend1 * document.getElementById(id).value;
}
document.getElementById("extend1").value = extend1;
summate();
}
function multiply2() {
var extend2 = 1;
for (var i = 1; i <= 2; i++) {
var id = "2_value" + i;
extend2 = extend2 * document.getElementById(id).value;
}
document.getElementById("extend2").value = extend2;
summate();
}
function multiply3() {
var extend3 = 1;
for (var i = 1; i <= 2; i++) {
var id = "3_value" + i;
extend3 = extend3 * document.getElementById(id).value ;
}
document.getElementById("extend3").value = extend3;
summate();
}
function multiply4() {
var extend4 = 1;
for (var i = 1; i <= 2; i++) {
var id = "4_value" + i;
extend4 = extend4 * document.getElementById(id).value;
}
document.getElementById("extend4").value = extend4;
summate();
}
function multiply5() {
var extend5 = 1;
for (var i = 1; i <= 2; i++) {
var id = "5_value" + i;
extend5 = extend5 * document.getElementById(id).value;
}
document.getElementById("extend5").value = extend5;
summate();
}
function summate() {
var material = 0;
for (var i = 1; i <= 5; i++) {
var id = "extend" + i;
material = material + document.getElementById(id).value * 1;
}
document.getElementById("material").value = material;
}
I think I understand what you're asking: The onchange event is not firing for the material box because it is being changed programatically, and therefore will not fire.
You can fire this function manually. It appears that you are modifying the material box in your summate() function. To make the material box register a change, add the following line to the very end of the summate() function:
document.getElementById("material").onchange();
Hopefully that was what you wanted. I think you might have to add this sort of thing on some of the quantity or other fields as well if you want it to update whenever a box is modified.
EDIT: This will only work if you have the onchange attribute set for your material element (I noticed you changed it to oninput).
I have a table body that looks like the following:
<tbody>
<tr class="basket_main">
<td class="basket_item">
<input type="text" class="basket_qty_txt" id="ctl00_ctl00_main_body_content_main_content_area_shopping_basket_ctl01_txt_qty_162" value="3" name="ctl00$ctl00$main_body_content$main_content_area$shopping_basket$ctl01$txt_qty_162">
</td>
<td class="basket_item prod_code" id="ctl00_ctl00_main_body_content_main_content_area_shopping_basket_ctl01_prod_code_col">
CSM160
</td>
<td class="basket_item">
SIL.MTG:RENAULT R19 1988 ON
</td>
<td class="basket_item max_qty">
5
</td>
<td class="basket_item">
<input type="button" class="basket_item_button">
<input type="button" class="basket_item_button">
</td>
</tr>
</tbody>
There could be many rows in this table, what I'm trying to find out is if the prod_code appears in more than one row in the table using javascript or jquery.
Iterate through the table cells and collect the data.
Live demo http://jsfiddle.net/kEAzB/6/
var items = {};
$('tr td.basket_item.prod_code').each(function(){
var value = $(this).text();
if (items[value] == undefined) {
items[value] = 0;
}
items[value] += 1;
});
for (key in items) {
alert(key + ":" +items[key]);
}
You could scan all the table rows, store the product codes in an Associative Array (ie productCodes and check if the same product code is already defined.
var productCodesTds = document.getElementsByClassName("prod_code"),
productCodes = Object.create(null),
max,
i;
for (i = 0, max = productCodesTds; i < max; i += 1) {
productCode = productCodesTds[i].innerText;
if (productCode in productCodes) {
// the productCode is already defined in an other td
}
else {
productCodes['productCode'] = null;
}
}
push all the codes to array
var arr = new Array();
$('.prod_code').each(function(){
var prod_code = $(this).val();
arr.push(prod_code);
});
sort the array and check if there are duplicate values
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i += 1) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
alert("duplicate value"+sorted_arr[i + 1]);
}
}