Total of a particular column from html table having multiple rows - javascript

My Java Script Code
<script>
$(function(){
$('#addRow').click(function(){
var html = $('#row_template').html();
$('#dataTable').append(html);
$(".tablerow").each(function(index) {
$(this).html(index + 1);
});
});
$('#deleteRow').click(function(){
$('#dataTable .mychkbox:checked').parents('tr').remove();
});
$('#dataTable').on('change','.select-desc',function(){
var cur_val = $(this).val();
$(this).parents('tr').find('input[name="rate[]"]').val(cur_val);
});
$('#dataTable').on('keyup','input[name="qty[]"]', function(){
var qty = +$(this).val();
var unit = +$(this).parents('tr').find('input[name="rate[]"]').val();
$(this).parents('tr').find('input[name="amt[]"]').val(qty*unit);
var totamt = 0 ;
var theTbl = document.getElementById('dataTable');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
totamt = totamt + theTbl.rows[i].cells[4].InnerHTML;
}
}
});
});
</script>
My HTML Code is
<!DOCTYPE html>
<html>
<div class="left">
<h2><span class="orange">Work Order Items</span></h2>
<table>
<tr>
<td><input type="button" value="Add Row" id="addRow" /></td>
<td><input type="button" value="Remove Row" id="deleteRow" /></td>
</tr>
</table>
</div>
<table id="dataTable" class="form" border="0" width='100%'>
<tr>
<td></td>
<td>No</td>
<td>Item Description</label></td>
<td>Qty</td>
<td>Rate</td>
<td>Amount</td>
<td>Cert No</td>
<td>C Date</td>
</tr>
</table>
<table id="row_template" style="display:none">
<tr>
<td><input type="checkbox" name="chk[]" class="mychkbox" /></td>
<td class="tablerow"></td>
<td>
<?php
$sql = "SELECT itrate,CONCAT(itname,'|',itcode) as mname FROM ITMAST ";
$result = mysql_query($sql) or die(mysql_error());
echo "<select name='itname[]' id='itname' class='select-desc' >";
echo "<option value=''>-- Select Item --</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value = '{$row['itrate']}'";
if ($pitcode == $row['itrate'])
echo "selected = 'selected'";
echo ">{$row['mname']}</option>";
}
echo "</select>";
?>
</td>
<td><input type="text" name="qty[]" id="qty" size="6" class='rightJustified'></td>
<td><input type="text" name="rate[]" id="rate" size="8" class='rightJustified' readonly></td>
<td><input type="text" name="amt[]" id="amt" size="9" class='rightJustified' readonly></td>
<td><input type="text" maxlength="10" size="8" name="txtcertno[]"></td>
<td><input type="date" maxlength="10" size="10" name="txtcdate[]"></td>
</tr>
</table>
</html>
I am trying to take total of amount column i.e. amt[] after each entry of a row, but I am not getting it properly, I have written Javascript function for the same but some thing may be wrong in it

I did not correct all of your mistakes,
You should check #Samurai answer for more details (such as use of the 'id' and other things)
Main problem was, as I said in comment, use of innerHTML which returned "
another thing, your theTbl var was not good, you could never call .length on it. To solve that, you had to handle it this way :
var totamt = 0 ;
var theTbl = $('#dataTable');
//You are using jquery, so use jquery selectors...
var trs = theTbl.find("input[name='amt[]']");
//find there the AMT[] INPUTS, not the rows...
console.log("how many amt inputs? : "+trs.length);
for(var i=0;i<trs.length;i++)
{
//fetch the inputs, and make your calculations here
console.log("amount from row "+i+" = "+trs[i].value);
//do not forget, as Samurai said, to convert html to numeric...
$("#total").html(totamt+=parseFloat(trs[i].value));
}
Here is a working solution :
http://jsfiddle.net/nxm0ye54/20/

First to point out a few mistakes:
$('#row_template').html(): browsers automatically add tbody to the table, so you end up having multiple tbody in your main table which of course won't cause any problem on its own, if that's the desired output.
You're misusing ID. Each tr has multiple td with inputs that share the same ID. Instead you should use class.
To calculate the total amount you're getting the innerHTML of the cells which don't hold a number, but an input element. Instead you want the value these input elements are holding.
You need to convert the values to numbers before doing math on them, otherwise it will assume they're string and just put them beside each other. (e.g. 0+1+2 = 012 and not 3). You should use parseInt or parseFlout which the latter suits this case better.
A few modifications to your code:
$('#addRow').click(function () {
var html = $('#row_template tbody').html();
$('#dataTable tbody').append(html);
And - since you're using jQuery - I completely changed the calculation to a jQuery version:
//gt(0) cause the first row contains headers
//eq(5) cause we want the 6th cell (Amount)
var totamt = 0;
$('#dataTable tr:gt(0)').each(function() {
var newAmt = $(this).find('td:eq(5) input[type=text]').val();
totamt += parseFloat(newAmt);
});

Related

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

How to get the value of input type text from the last row of a table

I have a table in my page and i have input type text in each row, one of them is for srno
I want to get the value of srno text box from the last row of the table using JavaScript.
Here's a code snippet with my HTML:
<table id="vattable" class="table table-sm table-striped">
<thead class="thead-light">
<tr>
<th style="width:50px">SRNo</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="text-control input-sm" readonly name="srno[]" id="srno" value=1 style="text-align:right;max-width:40px;" maxlength="13" /></td>
</tr>
</tbody>
</table>
Actually I am adding rows on button click event in JavaScript, I want to get the last value of srno column and give the next srno with +1 each time the row is created in the table. when the page is loaded I am selecting data from database and fetching in this table so sometime this table may have few rows already and when I click button to create row it should take the last srno and add +1 to the new row srno.
I think that this should work for you if you have a similar HTML structure.
What it basically does is:
Scanning the table structure for all inputs with name=srno.
Getting the last input and logging in the javascript console.
You can get its value with lastInput.value.
function getLastInput() {
//get all inputs with name srno in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
return lastInput;
}
$(document).ready(function() {
var rowcnt = $('#vattable tr').length;
var count = rowcnt;
$(document).on('click', '#addrow', function() {
count = count + 1;
var html_code = '';
html_code += '<tr id="row_id_' + count + '">';
html_code += '<td><input type="text" class="text-control input-sm" name="srno[]" id="srno" readonly style="text-align:right;width:40px" value="' + count + '"/></td>';
html_code += '</tr>';
$('#vattable').append(html_code);
console.log(getLastInput());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="vattable">
<tr>
<td>
<input type="text" name="srno[]" value="1" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="2" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="3" />
</td>
</tr>
<tr>
<td>
<input type="text" name="srno[]" value="4" />
</td>
</tr>
</table>
<button id="addrow">Add row</button>
EDIT:
Use this if your input name is srno[].
//get all inputs with name srno[] in an array
const allInputs = document.querySelectorAll('table tr input[name="srno[]"]');
//get the last input from the array by referring the highest index of the array
const lastInput = allInputs[allInputs.length - 1];
console.log(lastInput);

Javascript- Add row dynamically contain dropbox and formula

I have a table consist of 5 column: Code, Name, Qty, Price, and Total.
Code contain a dropbox menu which dynamically retrieve from another table. If user click the dropbox and select a code, name of the item will appear automatically in Name column.
For Total column, the value will appear from multiplying Qty and Price. The multiply script I used is:
<script language="javascript" type="text/javascript">
function multiply()
{
a=Number(document.calculator.qty.value);
b=Number(document.calculator.price.value);
c=a*b;
document.calculator.total.value=c;
}
</script>
My code for the table as below:
<table id="theTable" border="1">
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr id="templateRow">
<td type="text" name="code" id="code"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("inventory");
$result = mysql_query("select * from input_code_data");
$jsArray = "var code = new Array();\n";
echo '<select name="code" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['code'] . '">' . $row['code'] . '</option>';
$jsArray .= "code['" . $row['code'] . "'] = {name:'" . addslashes($row['name']) . "',desc:'".addslashes($row['name'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="name" id="name"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('code').value = code[id].name;
document.getElementById('name').value = code[id].desc;
};
</script>
</td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td><input type="text" name="total" /readonly><INPUT type="button" value="Click" onclick="javascript:multiply();"></td>
</tr>
</tbody>
</table>
<INPUT type='button' value='+' onclick="addRow('theTable')" />
If I click add row, then a new row will appear and the format is right. The problem is, when I select a code (from the dropbox) in second row, the name appear in the first row instead, not in the second row. Another problem, Click button for multiply isn't working in the second row.
Would anybody tell me how I fix this? Thanks.
It's because your changeValue(id) function is being called with the select field's value, not the row Id. Additionally, you're getting element by static id's instead of passing them in. HTML assumes that an Id will only appear once per page, you're breaking that so it always returns the first match.
EDIT for some example code:
This deals with some of the issues (if I'm understanding you properly). You might find the MDN docs helpful around how ids and other selectors work.
multiply suffers from the same issues as your original code, but you should be able to figure it out based on what is below:
<table id="theTable" border="1">
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr class="templateRow" id="invoice-line-1">
<td class="code">
<select onchange="changeValue(this.value, 'invoice-line-1')">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<!-- etc. -->
</select>
<span></span>
</td>
<td class="name"></td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td>
<input type="text" name="total" /readonly>
<input type="button" value="Click" onclick="javascript:multiply();">
</td>
</tr>
</tbody>
</table>
<input type='button' value='+' onclick="addRow('theTable')" />
<script type="text/javascript">
var codes = {
"1": {value: 1, name: "Option 1"},
"2": {value: 2, name: "Option 2"},
// etc.
},
numRows = 1;
function changeValue(value, id){
document.querySelector('#' + id + ' td.name').innerHTML = codes[value].name;
document.querySelector('#' + id + ' td.code > span').innerHTML = code[value].value;
};
function addRow() {
var newRow = document.getElementById("invoice-line-1").cloneNode(true),
table = document.querySelector("#theTable > tbody");
newRow.id = "invoice-line-" + (numRows = numRows + 1);
table.appendChild(rewRow);
document.querySelector("#invoice-line-" + numRows + " .code > select").setAttribute('onchange', "changeValue(this.value, 'invoice-line-" + numRows + "')");
}
</script>

adding values to unknown element ids in jquery

I have a dynamically created form in that a user can click "add row" and get a new element in the form.
some of the elements are quantity and price. I want to change values based on what users enter. so if he chooses qty=4 and price=10 i want amount to =40.
I dont know what to use as the selector for price or amount since input ids are dynamically generated.
var form = "<tr><td>Quantity</td>
<td><input class='qty' type='text' id='qty[]' name='qty[]'></td>";
form += "<td>Part Num</td>
<td><input type='text' id='part[]' name='part[]'></td>";
form += "<td>Description</td>
<td><input class='desc' type='text' id='desc[]' name='desc[]'></td>";
form += "<td>Unit Price</td>
<td><input type='text' id='price[]' name='price[]'></td>";
form += "<td>Amount</td>
<td><input type='text' id='amount[]' name='amount'></td></tr>";
$('#addItem').click(function(){
$('#itemsTable').append(form);
});
$(document).on('change','.qty',function(){
//What can i use as a selector for value_of_qty and value_of_price here???
//var total = $(value_of_qty) * $(value_of_price);
//$(id_of_amount).val(total);
});
on form submissions i see the following:
[qty] => Array
(
[0] => asdfdasf
[1] => asdfdasf
)
and so on....
You have (roughly) this structure:
<tr>
<td><input class="qty"></td>
<td><input name="price[]"></td>
</tr>
So, given that you have the .qty input, all you need to do is rise to the tr and get its input[name='price[]']. In code:
$(document).on('change','.qty',function(){
var $qty = $(this);
var $price = $qty.closest("tr").find("input[name='price[]']");
});
As I described in my comment, your HTML is invalid because you have duplicate ids. You should dynamically generate the HTML you append to the parent element, and assign a unique id value with each appendage. Here's what I would do:
var g_ROWNUM = 1;
$('#addItem').click(function() {
var form = '\
<tr>\
<td>Quantity</td><td><input class="qty" type="text" id="qty_${num}" name="qty[]"></td>\
<td>Part Num</td><td><input type="text" id="part_${num}" name="part[]"></td>\
<td>Description</td><td><input class="desc" type="text" id="desc_${num}" name="desc[]"></td>\
<td>Unit Price</td><td><input type="text" id="price_${num}" name="price[]"></td>\
<td>Amount</td><td><input type="text" id="amount_${num}" name="amount[]"></td>\
</tr>\
'.replace(/\$\{num\}/g,g_ROWNUM++);
$('#itemsTable').append(form);
});
$(document).on('change', '.qty', function() {
var qtyInput = $(this);
var num = qtyInput.attr('id').replace(/^qty_/,'');
var priceInput = $('#price_'+num);
var amountInput = $('#amount_'+num);
var total = qtyInput.val()*priceInput.val();
amountInput.val(total);
});
As you can see, this allows you to extract the generated number and use it to retrieve the price and amount elements in the same row as the changed quantity element, and then apply any dynamic changes you want to the elements in that row.
http://jsfiddle.net/p6wrkne4/1/
you should restructure your html by adding classes like this:
<tr class="tableRow">
<td>Quantity</td>
<td><input class='qty' type='text' id='qty[]' name='qty[]'/></td><td>Part Num</td>
<td><input type='text' id='part[]' name='part[]'/></td>
<td>Description</td>
<td><input class='desc' type='text' id='desc[]' name='desc[]'/></td>
<td>Unit Price</td>
<td><input type='text' class="price" id='price[]' name='price[]'/></td>
<td>Amount</td>
<td><input type='text' class="amount" id='amount[]' name='amount'/></td>
</tr>
$(document).on('change', '.qty', function() {
var qty = $(this).val();
var price = $(this).closest('.tableRow').find('.price').val();
var total = qty * price;
$(this).closest('.tableRow').find('.amount').val(total);
});
Try this code:
$(document).on('change','.qty',function(){
var qtyInput = $(this);
var price = qtyInput.closest("tr").find("input[name='price[]']").val();
var amount = qtyInput.val() * price;
qtyInput.closest("tr").find("input[name=amount]").val(amount);
});

onKeyUp event calculation not working on the following rows from php generated forms except the first one

--------------------------------------------------
|No|Style No|Item Desc|Qty|Unit Price|Total Price|
--------------------------------------------------
|1 |Style 1 |Item 1 |44 |3.00 |132.00 |
|2 |Style 2 |Item 2 |3 |3.00 |9.00 |
|3 |Style 3 |Item 3 |23 |34.00 |782.00 |
|4 |Style 4 |Item 4 |56 |78.00 |4368.00 |
|5 |Style 5 |Item 5 |34 |58.00 |1972.00 |
--------------------------------------------------
(Submit button)
GRAND TOTAL: RM[_________ textbox] (Calculate Total button)
Alternatively this is the screenshot image:
http://img715.imageshack.us/img715/8885/calcs.jpg
I have this table with a forms generated from the PHP script based on the table in the database. I've been pulling my hair out figuring how to make the following rows after the first one to work with the onkeyup event using JavaScript. The first row (in the red squared box) as the screenshot link above, seems to work well for example if I change the value of "Qty" in the first row to "1" it will automatically calculate and produce an output of "Total Price" to "3.00" but not on the following rows where it does nothing whenever i insert a new value. Strangely it does calculate each rows including in the "GRAND TOTAL" textbox when I click on the "Calculate Total" button
I cannot seems to figure out what the problem really is and how to fix it. Any help would be greatly appreciated.
Below is the source code:
<?php require_once('Connections/rfps.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
?>
<html>
<head>
<script type="text/javascript">
function calc(idx) {
var price = parseFloat(document.getElementById("cost"+idx).value)*
parseFloat(document.getElementById("qty"+idx).value);
// alert(idx+":"+price);
document.getElementById("price"+idx).value= isNaN(price)?"0.00":price.toFixed(2);
}
function totalIt() {
var qtys = document.getElementsByName("qty[]");
var total=0;
for (var i=1;i<=qtys.length;i++) {
calc(i);
var price = parseFloat(document.getElementById("price"+i).value);
total += isNaN(price)?0:price;
}
document.getElementById("total").value=isNaN(total)?"0.00":total.toFixed(2)
}
window.onload=function() {
document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
}
</script>
</head>
<body>
<?php
$sql = "SELECT * FROM transaction_item";
$result = mysql_query($sql,$rfps) or die($sql."<br/><br/>".mysql_error());
//start a table
echo '<form name="form1" method="post" action="">
<table width="350px" border="1" style="border-collapse:collapse;">';
//start header of table
echo '<tr>
<th id="datatable" > <div align="center">No</div></th>
<th style="display:none;"><div align="center">Trans<br />Item<br />ID</div></th>
<th style="display:none;"><div align="center">Trans<br />Info<br />ID</div></th>
<th><div align="center">Style<br />No</div></th>
<th><div align="center">Item<br />Desc</div></th>
<th><div align="center">Qty</div></th>
<th><div align="center">Unit<br />Price</div></th>
<th formula="cost*qty"summary="sum"><div align="center">Total<br />Price</div></th>
</tr>';
//loop through all results
$i=1;
while($r=mysql_fetch_object($result)){
//print out table contents and add id into an array and email into an array
echo '<tr>
<td id="datatable"> <div align="center">'.$i.'</div></td>
<td style="display:none;"><div align="center">'.$r->trans_item_id.'</div></td>
<td style="display:none;"><div align="center">'.$r->trans_info_id.'</div></td>
<td><div align="center"><input type="text" id="style'.$i.'" name="style[]" value="'.$r->style_no.'" size="10" /></div></td>
<td><div align="center"><input type="text" id="item'.$i.'" name="item[]" value="'.$r->item_desc.'" size="25" /></div></td>
<td><div align="center"><input type="text" id="qty'.$i.'" name="qty[]" value="'.$r->qty.'" size="2" /></div></td>
<td><div align="center"><input type="text" id="cost'.$i.'" name="cost[]" value="'.$r->unit_price.'" size="5" /></div></td>
<td><div align="center"><input type="text" id="price'.$i.'" name="price[]" value="'.$r->total_price.'" size="6" /></div></td>
</tr>';
++$i;
}
//submit the form
echo'</table>
<input type="submit" name="Submit" value="Submit">
<p><strong>GRAND TOTAL: RM</strong>
<input type="text" readonly="readonly" id="total" />
<input type="button" value="Calculate Total" onclick="totalIt()" /></p>
</form>';
?>
</body>
</html>
Well, upon a quick glance, the problem is that you're only grabbing the first qty[] element and the first cost[] element, to add listeners to.
Have a look at the last bit of JavaScript, there -- the window.onload = function (){... part:
window.onload=function() {
document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
}
That's great, but it means that you're only grabbing the first box of each, and sending in "qty1" and "cost1" data.
Try this, instead:
window.onload = function () {
var qtyArr = document.getElementsByName("qty[]"),
costArr = document.getElementsByName("cost[]"),
length = qtyArr.length,
i = 0, func = null;
for (; i < length; i++) {
func = (function (i) { return function () { calc(i + 1); }; }(i));
qtyArr[i].onkeyup = func;
costArr[i].onkeyup = func;
}
};
The more-appropriate way of doing this might be to use event-delegation:
Listen to onkeyup on the entire table that contains these rows.
If the element that was edited (using onkeyup) is an element you want to use:
if (event.target.name === "qty[]" || event.target.name === "cost[]") {...}
Fire calc like so:
calc( event.target.id.replace("qty","").replace("cost","") );
First way should work fine, if you want a quick-and-dirty solution.

Categories

Resources